js实现urlencode
URL编码简介
URL编码(Percent-Encoding)是将特殊字符转换为%后跟两位十六进制数的格式。JavaScript提供原生方法实现这一功能。
使用encodeURIComponent
encodeURIComponent()是标准方法,会对除字母、数字和-_.!~*'()外的所有字符进行编码:
const encoded = encodeURIComponent('测试&data=123');
// 输出 "%E6%B5%8B%E8%AF%95%26data%3D123"
使用encodeURI
encodeURI()用于编码完整URL,不会编码保留字符(如:/?#[]@):
const encoded = encodeURI('https://example.com/测试');
// 输出 "https://example.com/%E6%B5%8B%E8%AF%95"
手动实现编码
需要自定义编码规则时可用此方法:
function customUrlEncode(str) {
return str.split('').map(char => {
const code = char.charCodeAt(0);
return code > 128 ? '%' + code.toString(16).toUpperCase() : char;
}).join('');
}
解码方法
使用decodeURIComponent()还原编码后的字符串:

const decoded = decodeURIComponent('%E6%B5%8B%E8%AF%95');
// 输出 "测试"
注意事项
- 编码查询参数时优先使用
encodeURIComponent - 处理完整URL时注意区分
encodeURI和encodeURIComponent的使用场景 - 空格会被编码为
%20(而非+)






