数据安全提示: 所有文本数据均在您的浏览器本地处理,不会上传到服务器。
Escape转换工具
JavaScript原生支持
当前操作:文本 → Escape编码 (encodeURIComponent)
输入文本
字符数: 0
编码选项
转换结果
转换结果将显示在这里...
等待输入...
长度: 0
使用示例
"Hello World!" → 编码
Hello%20World%21
"name=张三&age=30" → 编码
name%3D%E5%BC%A0%E4%B8%89%26age%3D30
"测试中文" → 编码
%E6%B5%8B%E8%AF%95%E4%B8%AD%E6%96%87
"Hello%20World%21" → 解码
Hello World!
Escape编码算法原理
JavaScript编码函数对比
escape()
已废弃的JavaScript函数,对ASCII字母数字字符和 @*+-./ 不编码。
escape("Hello World!")
// "Hello%20World%21"
已废弃
// "Hello%20World%21"
encodeURI()
对整个URL进行编码,保留URL组成部分,不编码: / ? & = 等URL特殊字符。
encodeURI("https://example.com/测试")
// "https://example.com/%E6%B5%8B%E8%AF%95"
用于完整URL
// "https://example.com/%E6%B5%8B%E8%AF%95"
encodeURIComponent()
对URL组件进行编码,编码所有非字母数字字符,适用于查询参数等。
encodeURIComponent("name=测试")
// "name%3D%E6%B5%8B%E8%AF%95"
用于URL组件
// "name%3D%E6%B5%8B%E8%AF%95"
字符编码规则
| 字符类型 | 示例字符 | encodeURI编码 | encodeURIComponent编码 | escape编码 | 说明 |
|---|---|---|---|---|---|
| 字母数字 | A 1 | A 1 | A 1 | A 1 | 基本不编码 |
| 空格 | 空格 | %20 | %20 | %20 | 编码为%20 |
| URL保留字符 | : / ? | : / ? | %3A %2F %3F | : / ? | encodeURIComponent编码 |
| 中文字符 | 中 | %E4%B8%AD | %E4%B8%AD | %u4E2D | UTF-8编码,escape为Unicode |
编码原理详解
// 编码过程伪代码
function encodeURIComponent(str) {
const result = [];
for (let i = 0; i < str.length; i++) {
const char = str[i];
if (char.match(/[A-Za-z0-9\-_.!~*'()]/)) {
result.push(char);
} else {
// 获取字符的UTF-8编码
const code = str.charCodeAt(i);
if (code < 128) {
result.push('%' + code.toString(16).toUpperCase());
} else {
const bytes = getUTF8Bytes(char);
for (const byte of bytes) {
result.push('%' + byte.toString(16).toUpperCase());
}
}
}
}
return result.join('');
}
function encodeURIComponent(str) {
const result = [];
for (let i = 0; i < str.length; i++) {
const char = str[i];
if (char.match(/[A-Za-z0-9\-_.!~*'()]/)) {
result.push(char);
} else {
// 获取字符的UTF-8编码
const code = str.charCodeAt(i);
if (code < 128) {
result.push('%' + code.toString(16).toUpperCase());
} else {
const bytes = getUTF8Bytes(char);
for (const byte of bytes) {
result.push('%' + byte.toString(16).toUpperCase());
}
}
}
}
return result.join('');
}
Escape编码应用场景
URL参数编码
在GET请求中传递特殊字符(如中文、空格、&等)时,必须进行URL编码。
fetch(`/api?name=${encodeURIComponent('张三')}&age=30`)
HTML属性值编码
在HTML标签属性中嵌入URL时,需要对特殊字符进行编码。
<a href="https://example.com?q=encodeURIComponent('测试')">链接</a>
Cookie值编码
Cookie值中不能包含分号、逗号等特殊字符,通常使用encodeURIComponent编码。
数据传输安全
对用户输入的数据进行编码,防止注入攻击(如XSS),但需注意上下文选择合适的编码方式。
JSONP请求
JSONP回调函数名需要编码,避免特殊字符破坏语法。