js实现urlencode
URL编码的实现方法
在JavaScript中,URL编码可以通过内置的encodeURIComponent()和encodeURI()函数实现。这两种方法有不同的使用场景和编码范围。
encodeURIComponent()方法
encodeURIComponent()会对所有非标准字符进行编码,包括保留字符(如?、&、=等)。适用于编码URI的组件部分(如查询参数)。

const originalString = "hello world?param=value";
const encodedString = encodeURIComponent(originalString);
// 输出: "hello%20world%3Fparam%3Dvalue"
encodeURI()方法
encodeURI()不会编码保留字符和特殊字符,适用于编码整个URI。主要用于编码完整的URL而非其中部分。
const url = "https://example.com/hello world?param=value";
const encodedUrl = encodeURI(url);
// 输出: "https://example.com/hello%20world?param=value"
手动实现URL编码
如果需要更细粒度的控制或特殊需求,可以手动实现URL编码函数:

function customUrlEncode(str) {
return str.replace(/[^\w\-_.~]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase();
});
}
解码URL编码
对应的解码函数有decodeURIComponent()和decodeURI():
const encoded = "hello%20world%3Fparam%3Dvalue";
const decoded = decodeURIComponent(encoded);
// 输出: "hello world?param=value"
注意事项
encodeURIComponent()比encodeURI()编码范围更广,适用于参数值编码。encodeURI()会保留URL结构字符,适用于完整URL编码。
对于特殊字符集或特定需求,可能需要结合使用这两种方法或实现自定义编码逻辑。






