JS中encodeURIComponent与decodeURIComponent、encodeURI和decodeURI的区别
Window atob() 方法
atob() 方法用于解码使用 base-64 编码的字符串。
base-64 编码使用方法是 btoa() 。
1-1、escape()函数: escape()函数可对字符串进行编码。
escape()编码字符串:
<script type="text/javascript"> document.write(escape("Visit W3School!") + "<br />") document.write(escape("?!=()#%&")) </script>
输出:
Visit%20W3School%21 %3F%21%3D%28%29%23%25%26
escape函数说明:http://www.w3school.com.cn/jsref/jsref_escape.asp
1-2、unescape()函数:unescape()函数可对通过escape()编码的字符串进行解码。
我们将使用escape()来编码字符串,然后使用unescape()对其解码:
<script type="text/javascript"> var test1="Visit W3School!" test1=escape(test1) document.write (test1 + "<br />") test1=unescape(test1) document.write(test1 + "<br />") </script>
输出:
Visit%20W3School%21
Visit W3School!
unescape函数: http://www.w3school.com.cn/jsref/jsref_unescape.asp
注释:ECMAScript v3 已从标准中删除了 unescape() 函数,并反对使用它,因此应该用decodeURI()和decodeURIComponent()取而代之。
2-1、encodeURI()函数:可把字符串作为URI进行编码。
我们将使用encodeURI()对URI进行编码:
<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/ ,/?:@&=+$#
encodeURI()函数: http://www.w3school.com.cn/jsref/jsref_encodeuri.asp
2-2、decodeURI() 函数:对encodeURI() 函数编码过得URI进行解码。
<script type="text/javascript"> var test1="http://www.w3school.com.cn/My first/" document.write(encodeURI(test1)+ "<br />") document.write(decodeURI(test1)) </script>
输出:
http://www.w3school.com.cn/My%20first/ http://www.w3school.com.cn/My first/
3-1、encodeURIComponent()函数:把字符串作为URI组件进行编码。
我们将使用encodeURIComponent()对URI进行编码:
<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
encodeURIComponent函数():http://www.w3school.com.cn/jsref/jsref_encodeURIComponent.asp
提示:请注意encodeURIComponent()函数与encodeURI() 函数的区别之处,前者假定它的参数是URI的一部分(比如协议,主机名,路径或查询字符串)。因此encodeURIComponent() 函数将转义用于分隔URI各个部分的标点符号。
3-2、decodeURIComponent() 函数:可对encodeURIComponent()函数编码的URI进行解码。
我们将使用decodeURIComponent()对编码后的URI进行解码:
<script type="text/javascript"> var test1="http://www.w3school.com.cn/My first/" document.write(encodeURIComponent(test1)+ "<br />") document.write(decodeURIComponent(test1)) </script>
输出:
http%3A%2F%2Fwww.w3school.com.cn%2FMy%20first%2F http://www.w3school.com.cn/My first/
decodeURIComponent()函数:http://www.w3school.com.cn/jsref/jsref_decodeURIComponent.asp