【JavaScript】 URI 编码与解码

encodeURI()和 encodeURIComponent()

encodeURI()和 encodeURIComponent()方法可以对 URI进行编码,以便发送给浏览器。有效的 URI 中不能包含某些字符,例如空格。而这两个 URI 编码方法就可以对 URI 进行编码,它们用特殊的 UTF-8 编码替换所有无效的字符,从而让浏览器能够接受和理解。

encodeURI()主要用于整个 URI进行编码
encodeURI()不会对本身属于 URI 的特殊字符进行编码,例如冒号、正斜杠、问号和井字号;
encodeURIComponent())主要用于对 URI 中的某一段进行编码
encodeURIComponent()会对它发现的任何非标准字符进行编码

var uri = "http://www.wrox.com/illegal value.htm#start"; 
console.log(encodeURI(uri)); 
//"http://www.wrox.com/illegal%20value.htm#start" 
//除了空格之外的其他字符都原封不动,只有空格被替换成了%20
console.log(encodeURIComponent(uri)); 
//"http%3A%2F%2Fwww.wrox.com%2Fillegal%20value.htm%23start" 
//使用对应的编码替换所有非字母数字字符

decodeURI()和decodeURIComponent()

与 encodeURI()和 encodeURIComponent()方法对应的两个方法分别是 decodeURI()和decodeURIComponent()。其中,decodeURI()只能对使用 encodeURI()替换的字符进行解码。例如,它可将%20 替换成一个空格,但不会对%23 作任何处理,因为%23 表示井字号(#),而井字号不是使用
encodeURI()替换的。同样地,decodeURIComponent()能够解码使用encodeURIComponent()编码的所有字符,即它可以解码任何特殊字符的编码。

var uri = "http%3A%2F%2Fwww.wrox.com%2Fillegal%20value.htm%23start"; 
console.log(decodeURI(uri)); 
//http%3A%2F%2Fwww.wrox.com%2Fillegal value.htm%23start
//只有%20 被替换成了空格
console.log(decodeURIComponent(uri));
//http://www.wrox.com/illegal value.htm#start
//所有特殊字符的编码都被替换成了原来的字符,得到了一个未经转义的字符串(但这个字符串并不是一个有效的 URI)。
发布了10 篇原创文章 · 获赞 1 · 访问量 302

猜你喜欢

转载自blog.csdn.net/AAABingBing/article/details/104159914
URI