encodeURIComponent()函数
可以把字符串作为URI组件进行编码
此函数对特殊字符进行编码。此外,它还对以下字符进行编码: , / ? : @ & = + $ #
以下举例说明
var uri = "https://w3school.com.cn/my test.asp?name=ståle&car=saab";
var res = encodeURIComponent(uri);
console.log(res) //结果为https%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab
decodeURIComponent()函数
对编码的URI组件进行解码
var uri = "https://w3schools.com/my test.asp?name=ståle&car=saab";
var uri_enc = encodeURIComponent(uri);//编码
var uri_dec = decodeURIComponent(uri_enc);//解码
var res = '编码:'+uri_enc + "<br>" +'解码'+ uri_dec;
console.log(res) //结果为 编码: https%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab
解码: https://w3schools.com/my test.asp?name=ståle&car=saab
题外话
问:为什么要进行编码?
答:在使用地址栏提交查询参数时,若不进行编码,非英文字符会按照操作系统的字符集进行编码提交到服务器,服务器会按照配置的字符集进行编码,若两者不一致会导致乱码