js解决url传递中文参数乱码问题的方法详解

https://www.jb51.net/article/283636.htm 原文链接

场景复现:
bug解决思路:

url传参中文乱码的解决方法
1、escape 和 unescape
2、encodeURI 和 decodeURI
3、encodeURIComponent 和 decodeURIComponent

总结

1、escape 和 unescape

escape()不能直接用于URL编码,它的真正作用是返回一个字符的Unicode编码值。

采用unicode字符集对指定的字符串除0-255以外进行编码。所有的空格符、标点符号、特殊字符以及更多有联系非ASCII字符都将被转化成%xx格式的字符编码(xx等于该字符在字符集表里面的编码的16进制数字)。比如,空格符对应的编码是%20。
escape不编码字符有69个:*,+,-,.,/,@,_,0-9,a-z,A-Z。

escape()函数用于js对字符串进行编码,不常用。

//跳转页
location.href = './test.html?'+escape('name=张三&age=18')
//接收页
var str = unescape(location.search.substr(1));
//url显示
'test.html?name%3D%u5F20%u4E09%26age%3D18'

2、encodeURI 和 decodeURI

把URI字符串采用UTF-8编码格式转化成escape各式的字符串。

encodeURI不编码字符有82个:!,#,$,&,',(,),*,+,,,-,.,/,:,;,=,?,@,_,~,0-9,a-z,A-Z

encodeURI()用于整个url编码。

//跳转页
location.href = encodeURI('./test.html?name=张三&age=18');
//接收页
var str = decodeURI(location.search.substr(1));
//url显示
'test.html?name=张三&age=18'

3、encodeURIComponent 和 decodeURIComponent

与encodeURI()的不同的是,“; / ? : @ & = + $ , #”,这些在encodeURI()中不被编码的符号,在encodeURIComponent()中统统会被编码。至于具体的编码方法,两者是一样。把URI字符串采用UTF-8编码格式转化成escape格式的字符串。

//跳转页
location.href = './test.html?'+encodeURIComponent('name=张三&age=18');
//接收页
var str = decodeURIComponent(location.search.substr(1));
//url显示
'test.html?name%3D张三%26age%3D18'

你可能感兴趣的:(javascript,前端,vue.js)