js urldecode实现
URL解码的基本概念
URL解码是将URL编码的字符串转换回原始字符串的过程。URL编码通常使用百分号(%)后跟两位十六进制数表示特殊字符。例如,空格被编码为%20。
使用decodeURIComponent实现
JavaScript提供了内置函数decodeURIComponent用于解码URL编码的字符串。该函数会解码所有URL编码的字符。
const encodedStr = 'Hello%20World%21';
const decodedStr = decodeURIComponent(encodedStr);
console.log(decodedStr); // 输出: Hello World!
手动实现URL解码
如果需要手动实现URL解码,可以通过正则表达式匹配百分号编码的字符并替换。
function urlDecode(str) {
return str.replace(/%([0-9A-F]{2})/gi, function(match, p1) {
return String.fromCharCode(parseInt(p1, 16));
});
}
const encodedStr = 'Hello%20World%21';
const decodedStr = urlDecode(encodedStr);
console.log(decodedStr); // 输出: Hello World!
处理特殊字符
decodeURIComponent会解码所有百分号编码的字符,包括/、?、#等。如果只需要解码部分字符,可以手动实现特定逻辑。
function customUrlDecode(str) {
return str.replace(/%20/g, ' ')
.replace(/%21/g, '!')
.replace(/%2F/g, '/');
}
const encodedStr = 'Hello%20World%21%2Ftest';
const decodedStr = customUrlDecode(encodedStr);
console.log(decodedStr); // 输出: Hello World!/test
注意事项
使用decodeURIComponent时,如果字符串包含无效的百分号编码(如%XX中XX不是有效的十六进制数),会抛出错误。可以通过try-catch处理异常。

try {
const decodedStr = decodeURIComponent('%ZZ');
console.log(decodedStr);
} catch (e) {
console.error('Invalid URL encoding:', e.message);
}
性能考虑
对于大量数据的解码,decodeURIComponent通常比手动实现更快,因为它是原生函数。手动实现适用于需要自定义解码逻辑的场景。






