JavaScript中有几个可以对字符串编码的函数,分别是:escape、encodeURI、encodeURIComponent。
1. escape
const a1 = 'Visit W3School!'; const b1 = '?!=()#%&' console.log(escape(a1)); // Visit%20W3School%21 console.log(escape(b1)); // %3F%21%3D%28%29%23%25%26 const a2 = 'Visit%20W3School%21'; const b2 = '3F%21%3D%28%29%23%25%26'; console.log(unescape(a2)); // Visit W3School! console.log(unescape(b2)); // ?!=()#%&
2. encodeURI
const a1 = 'http://www.w3school.com.cn/My first/'; const b1 = ',/?:@&=+$#' console.log(encodeURI(a1)); // http://www.w3school.com.cn/My%20first/ console.log(encodeURI(b1)); // ,/?:@&=+$# const a2 = 'http://www.w3school.com.cn/My%20first/'; const b2 = ',/?:@&=+$#'; console.log(decodeURI(a2)); // http://www.w3school.com.cn/My first/ console.log(decodeURI(b2)); // ,/?:@&=+$#
3. encodeURIComponent
const a1 = 'http://www.w3school.com.cn/My first/'; const b1 = ',/?:@&=+$#' console.log(encodeURIComponent(a1)); // http%3A%2F%2Fwww.w3school.com.cn%2FMy%20first%2F console.log(encodeURIComponent(b1)); // ,%2C%2F%3F%3A%40%26%3D%2B%24%23 const a2 = 'http%3A%2F%2Fwww.w3school.com.cn%2FMy%20first%2F'; const b2 = '%2C%2F%3F%3A%40%26%3D%2B%24%23'; console.log(decodeURIComponent(a2)); // http://www.w3school.com.cn/My first/ console.log(decodeURIComponent(b2)); // ,/?:@&=+$#
总结:
通过对三个函数的分析,我们知道:escape() 除了 ASCII 字母、数字和特定的符号外,对传进来的字符串全部进行转义编码,因此如果想对 URL 编码,最好不要使用此方法。而 encodeURI() 用于编码整个 URI,因为 URI 中的合法字符都不会被编码转换。encodeURIComponent 方法在编码单个 URIComponent(指请求参数)应当是最常用的,它可以讲参数中的中文、特殊字符进行转义,而不会影响整个URL。