js urldecode 实现
URL 解码实现方法
在 JavaScript 中,URL 解码可以通过内置的 decodeURIComponent() 函数实现。该函数用于解码由 encodeURIComponent() 编码的 URI 组件。
基本用法:
const encodedStr = 'Hello%20World%21';
const decodedStr = decodeURIComponent(encodedStr);
console.log(decodedStr); // 输出: "Hello World!"
处理异常情况
decodeURIComponent() 在遇到无效编码时会抛出错误。为避免程序中断,可以结合 try-catch 处理异常:
function safeDecodeURIComponent(str) {
try {
return decodeURIComponent(str);
} catch (e) {
console.warn('解码失败:', e.message);
return str; // 返回原字符串或自定义处理
}
}
替代方案
如果需兼容特殊字符(如 % 未跟随十六进制数),可使用以下方法:
function customDecodeURI(str) {
return str.replace(/%([0-9A-F]{2})/gi, (match, p1) => {
return String.fromCharCode(parseInt(p1, 16));
});
}
注意事项
decodeURI()与decodeURIComponent()区别:前者不解码#,&,=等保留字符,后者会解码所有编码字符。- 编码字符串通常来自 URL 的查询参数(
location.search),需先提取再解码:
const params = new URLSearchParams('?q=JavaScript%20%26%20HTML');
console.log(params.get('q')); // 自动解码输出: "JavaScript & HTML"






