一.区别.
- 这两个函数功能上面比较接近,但是有一些区别。
- encodeURI:不会进行编码的字符有82个 :!,#,$,&,’,(,),*,+,,,-,.,/,:,;,=,?,@,_,~,0-9,a-z,A-Z
- encodeURIComponent:不会进行编码的字符有71个:!, ',(,),*,-,.,_,~,0-9,a-z,A-Z
二.总结.
encodeURI() 用于编码整个URI,因为URI中的合法字符都不会被编码转换。encodeURIComponent方法在编码单个URIComponent(指请求参数)应当是最常用的,它可以讲参数中的中文、特殊字符进行转义,而不会影响整个URL。
三.示例.
1、 encodeURI()
<script type="text/javascript">
document.write(encodeURI("http://www.w3school.com.cn/")+ "<br />")
document.write(encodeURI("http://www.w3school.com.cn/My first/"))
document.write(encodeURI(",/?:@&=+$#"))
</script>输出:
http://www.w3school.com.cn/
http://www.w3school.com.cn/My%20first/
,/?:@&=+$#
对整个URL进行编码,而URL的特定标识符不会被转码。
2、 encodeURIComponent()
例1:
<script type="text/javascript">
document.write(encodeURIComponent("http://www.w3school.com.cn/"))
document.write("<br />")
document.write(encodeURIComponent("http://www.w3school.com.cn/p 1/"))
document.write("<br />")
document.write(encodeURIComponent(",/?:@&=+$#"))
</script输出:
http%3A%2F%2Fwww.w3school.com.cn
http%3A%2F%2Fwww.w3school.com.cn%2Fp%201%2F
%2C%2F%3F%3A%40%26%3D%2B%24%23
例2:<script language="javascript">document.write('
<a href="http://passport.baidu.com/?logout&aid=7&u='+encodeURIComponent("http://cang.baidu.com/bruce42")+'">退出</a>');</script>
对URL中的参数进行编码,因为参数也是一个URL,如果不编码会影响整个URL的跳转。
四.
关于escape说两点:
ECMAScript 3中已经不提倡使用这个函数了,所以我们还是少用吧。
escape不会编码的字符有69个:*,+,-,.,/,@,_,0-9,a-z,A-Z