JS对字符串编码的几种方式使用指南

  作者:bea

函数描述 encodeURI()把字符串编码为 URI encodeURIComponent()把字符串编码为 URI 组件 escape()对字符串进行编码 上面是查询来自w3school的资料。那么三者之间有什么区别呢,请容我测试测试。 代码如下: var str = " http://localhost:8080/Product/index?id=123&attr=456&area=中国"; console.log(encodeURI(str))
函数 描述 encodeURI() 把字符串编码为 URI encodeURIComponent() 把字符串编码为 URI 组件 escape() 对字符串进行编码
上面是查询来自w3school的资料。那么三者之间有什么区别呢,请容我测试测试。


代码如下:


var str = "
http://localhost:8080/Product/index?id=123&attr=456&area=中国";
console.log(encodeURI(str));
console.log(encodeURIComponent(str));
console.log(escape(str));



打印结果如下:


代码如下:



http://localhost:8080/Product/index?id=123&attr=456&area=%E4%B8%AD%E5%9B%BD
http%3A%2F%2Flocalhost%3A8080%2FProduct%2Findex%3Fid%3D123%26attr%3D456%26area%3D%E4%B8%AD%E5%9B%BD
http%3A//localhost%3A8080/Product/index%3Fid%3D123%26attr%3D456%26area%3D%u4E2D%u56FD



可以看出,
encodeURI不会对:/?&等uri中起分割作用的字符进行编码;
encodeURIComponent则会。
观察escape则发现,:?&都被转码了,而/没有,w3school解释是,escape函数会对ascii码中字母、数字及符号( * @ - _ + . / )之外的所有字符进行编码。
另外,我们可以看出escape对汉字“中国”编码后结果与前两者不同。W3SCHOOL也建议不使用该方法,用前两者代替。
以上所述就是本文的全部内容了,希望对大家学习javascript能够有所帮助。


有用  |  无用

猜你喜欢