JS基本语法-JavaScript中的常用函数4:encodeURI() ,decodeURI(),encodeURIComponent(),decodeURIComponent()等编码和解码URI
1. 简介:
我们经常需要对URI进行编码和解码,在JavaScript中,提供了encodeURI() ,decodeURI(),encodeURIComponent(),decodeURIComponent()等编码和解码URI的内部函数。
URI,统一资源标志符(Uniform Resource Identifier, URI),表示的是web上每一种可用的资源,如 HTML文档、图像、视频片段、程序等都由一个URI进行标识的。
2. encodeURI() 和decodeURI()使用举例:
.encodeURI(uri):对参数uri进行编码,uri为字符串。
encodeURI()函数只对字符串中有意义的字符进行转义。例如将字符串中的空格转化为“%20”。
.decodeURI(uri):解码已经编码的字符串。
decodeURI()是encodeURI()函数的逆向操作。
代码举例:
encode.js:
function endecode_test(){var uri = "http://127.0.0.1/test.html?name=张三&age=30";var encodeResStr = encodeURI(uri); console.log(encodeResStr); console.log(decodeURI(encodeResStr)); }
encode.html:
JavaScript中的常用函数4:编码URI和解码URI
结果:
endecode_test();
运行结果:
在控制台可以看到:
encodeRes = http://127.0.0.1/test.html?name=%E5%BC%A0%E4%B8%89&age=30
encode.js:5decodeRes = http://127.0.0.1/test.html?name=张三&age=30
3. encodeURIComponent() 和decodeURIComponent()使用举例:
.encodeURIComponent(uri):字符串作为 URI 组件进行编码,uri为字符串。
encodeURIComponent()方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ * ' ( ) 。
所谓组件,通常会被如下符号分割的字符串::;/?:@&=+$,# 。
.decodeURIComponent(uri):解码已经编码的字符串,是encodeURIComponent()函数的逆向操作。
代码举例:
encode.js:
function endecodeURIComponent_test(){var uri = "http://127.0.0.1/test.html?name=张三&age=30";var encodeResStr = encodeURIComponent(uri); console.log("encodeRes = " + encodeResStr); console.log("decodeRes = " + decodeURIComponent(encodeResStr)); }
encode.html:
JavaScript中的常用函数4:编码URI和解码URI
结果:
endecodeURIComponent_test();
运行结果:
encodeRes = http%3A%2F%2F127.0.0.1%2Ftest.html%3Fname%3D%E5%BC%A0%E4%B8%89%26age%3D30
encode.js:12decodeRes = http://127.0.0.1/test.html?name=张三&age=30
说明:
encodeURIComponent()和encodeURI()的最主要区别是:前者对保留字符同样做转义编码,后者则不会。