decodeURI 与 decodeURIComponent 区别

decodeURI 与 decodeURIComponent 区别,第1张

decodeURI 与 decodeURIComponent 区别

1. 关于URL、encodeURI 及 encodeURIComponent:

URI: Uniform Resource Identifiers,通用资源标识符

Global 对象的 encodeURI() 和 encodeURIComponent() 方法可以对 URI 进行编码,以便发送给浏览器。


有效的 URI 中不能包含某些字符,例如空格


而这 URI 编码方法就可以对 URI 进行编码,它们用特殊的 UTF-8 编码替换所有无效的字符,从而让浏览器能够接受和理解。


其中 encodeURI() 主要用于整个 URI (例如,http://www.jxbh.cn/illegal value.htm),而 encode-URIComponent() 主要用于对 URI 中的某一段(例如前面 URI 中的 illegal value.htm)进行编码。


它们的主要区别在于,encodeURI() 不会对本身属于 URI 的特殊字符进行编码,例如冒号、正斜杠、问号和 # 字号;而 encodeURIComponent() 则会对它发现的任何非标准字符进行编码。


来看下面的例子:

var uri="http://www.jxbh.cn/illegal value.htm#start";
//”http: //www.jxbh.cn/illegal%20value .htm#s tart”
alert(encodeURI (uri)):
//”http% 3A%2F%2Fwww.jxbh.cn%2 Fillegal%2 0value. htm%23 start”
alert( encodaURIComponent (uri));

使用 encodeURI() 编码后的结果是除了空格之外的其他字符都原封不动,只有空格被替换成了 %20。


而 encodeURIComponent() 方法则会使用对应的编码替换所有非字母数字字符。


这也正是可以对整个 URI 使用 encodeURI(),而只能对附加在现有 URI 后面的字符串使用 encodeURIComponent() 的原因所在。


一般来说,我们使用 encodeURIComponent() 方法的时候要比使用 encodeURI() 更多,因为在实践中更常见的是对查询字符串参数而不是对基础 URL 进行编码。


2. 关于 decodeURI、decodeURIComponent:

了解了 encodeURI 与 encodeURIComponent 的区别后,我们来看下 decodeURI 与 decodeURIComponent。


总结:最好使用 decodeURIComponent() 进行解码。


防止中文乱码方法: decodeURIComponent(数据,true)

3. 一个小考题:

// 请解码被多次编码的 URL
例子:https%253A%252F%252Fwww.baidu.com%252F%253Ftest%253D1
条件:被编码次数未知 结果:https://www.baidu.com/?test=1

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/585710.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-12
下一篇 2022-04-12

发表评论

登录后才能评论

评论列表(0条)

保存