js urldecode 实现
URL解码的实现方法
JavaScript提供了内置函数decodeURIComponent()用于解码URL编码的字符串。以下是几种实现URL解码的方法:

使用decodeURIComponent函数
const encodedUrl = 'Hello%20World%21';
const decodedUrl = decodeURIComponent(encodedUrl);
console.log(decodedUrl); // 输出: Hello World!
处理异常情况
当字符串包含无效的编码序列时,decodeURIComponent会抛出URIError异常,可以使用try-catch处理:

function safeDecodeURIComponent(encoded) {
try {
return decodeURIComponent(encoded);
} catch (e) {
console.error('无效的URI编码:', encoded);
return encoded; // 返回原始字符串或处理错误
}
}
自定义URL解码实现
如果需要自定义实现,可以使用正则表达式替换编码字符:
function customUrldecode(str) {
return str.replace(/%([0-9A-F]{2})/gi, function(match, p1) {
return String.fromCharCode(parseInt(p1, 16));
});
}
处理完整URL
如果需要解码整个URL而不仅仅是查询参数部分:
function decodeFullUrl(url) {
return url.split('?').map((part, i) => {
return i === 0 ? part : decodeURIComponent(part);
}).join('?');
}
注意事项
decodeURIComponent不会解码decodeURI保留的字符(如/,?,=等)- 编码字符串必须使用UTF-8编码
- 对于现代浏览器,这些方法都能正确处理非ASCII字符






