js实现urlencode
URL编码简介
URL编码(Percent-Encoding)是将URL中的特殊字符转换为%后跟两位十六进制数的形式。JavaScript提供了原生方法实现这一功能。
使用encodeURIComponent
最常用的方法是使用encodeURIComponent()函数,它会对所有非字母数字字符进行编码(包括! ' ( )等):
const encoded = encodeURIComponent('测试&data=123');
console.log(encoded); // 输出 "%E6%B5%8B%E8%AF%95%26data%3D123"
使用encodeURI
当需要编码完整URL时(保留协议、域名等部分),使用encodeURI()。它不会编码:/?#[]@等URL保留字符:
const url = 'https://example.com/测试?name=张三';
console.log(encodeURI(url)); // 输出 "https://example.com/%E6%B5%8B%E8%AF%95?name=%E5%BC%A0%E4%B8%89"
手动实现编码
如需自定义编码规则,可通过以下函数实现:

function customUrlEncode(str) {
return str.split('').map(char => {
const code = char.charCodeAt(0);
return code > 128 || char === ' ' ? '%' + code.toString(16).toUpperCase() : char;
}).join('');
}
注意事项
encodeURIComponent会编码更多字符(包括?&=等),适合编码URL参数值- 空格在URL编码中可以是
%20或+,需根据服务器要求处理 - 现代浏览器已自动处理URL编码,手动编码主要用于特殊场景或Node.js环境






