JavaScript中对字符串编码的三个函数

2017-08-10  本文已影响93人  7天苹果

JavaScript中有三个可以对字符串编码的函数,分别是:

escape(),encodeURI(),encodeURIComponent()

相应3个解码函数:

unescape(),decodeURI(),decodeURIComponent()

1 .escape()函数

escape(string)

2 .encodeURI()函数

encodeURI(URIstring)

3 .encodeURIComponent() 函数

 encodeURIComponent(URIstring)

4 .总结:
通过对三个函数的分析,我们可以知道:escape()除了 ASCII 字母、数字和特定的符号外,对传进来的字符串全部进行转义编码,因此如果想对URL编码,最好不要使用此方法。
而encodeURI() 用于编码整个URI,因为URI中的合法字符都不会被编码转换。
encodeURIComponent方法在编码单个URIComponent(指请求参数)应当是最常用的,它可以将参数中的中文、特殊字符进行转义,而不会影响整个URL。

5 .示例:
escape()

<script type="text/javascript">

document.write(escape("http://www.w3school.com.cn/") + "<br />")

document.write(escape("?!=()#%&"))

</script>

输出:

http%3A//www.w3school.com.cn

%3F%21%3D%28%29%23%25%26

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的特定标识符(比如,/?:@&=+$#)不会被转码。

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的跳转。

上一篇 下一篇

猜你喜欢

热点阅读