Global(所有在全局作用域中定义的属性和函数,都是Global的属性)对象的encodeURI(),encodeURIComponent()方法可以对**URI(通用资源标识符)**进行编码,以便发送给浏览器。
有效的URI不能包含某些字符:例如空格。这2个URI编码方法就可以对URI进行编码,用特殊的UTF8编码替换所有无效的字符,从而让浏览器能够接受。
1.encodeURI(),encodeURIComponent()
先看个demo例子:
var uri = 'https://www.baidu.com/s?ie=utf-16&word=hello #index.html';
encodeURI(uri) //https://www.baidu.com/s?ie=utf-16&word=hello%20#index.html
encodeURIComponent(uri) //https%3A%2F%2Fwww.baidu.com%2Fs%3Fie%3Dutf-16%26word%3Dhello%20%23index.html
从上面的例子,可以看出:
encodeURI()编码后的结果是:空格被替换成了%20,除了空格之外的任何字符都没有改变;
encodeURIComponent()则是将所有非字母数字字符替换成对应编码。
encodeURI()可以对整个URI进行使用,而encodeURIComponent()只适用于对附加URI后面的字符串使用。
所以一般来说,我们使用更多的的是encodeURIComponent(),因为我们更需要对查询字符串进行编码,而不是整个URI
2.decodeURI(),decodeURIComponent()
这两个方法与encodeURI(),encodeURIComponent()对应,其中decodeURI()只能对使用encodeURI()替换的字符进行解码,decodeURIComponent()能对使用encodeURIComponent()替换的字符进行解码
var uri = 'https://www.baidu.com/s?ie=utf-16&word=hello%20%24#index.html';
decodeURI(uri) //https://www.baidu.com/s?ie=utf-16&word=hello %24#index.html
decodeURIComponent(uri) //https://www.baidu.com/s?ie=utf-16&word=hello $#index.html
因为uri中有编码值%20,%24,decodeURI只可以把%20转化为空格,不会对%24仅从任何处理,因为%24表示$符号,$符号不是使用encodeURI替换的。
而decodeURIComponent可以解释任何特殊字符的编码。
我们可以使用decodeURIComponent将URL Search 中的参数转化为对象,以便我们使用:
var str = 'https://www.sogou.com/sie?ie=utf8&query=%E5%91%B5%E5%91%B5&pid=AQKo5-0000';
var query = str.split('?')[1];
var result = {};
query.split("&").forEach(function(part) {
var item = part.split("=");
result[item[0]] = decodeURIComponent(item[1]);
});
console.log(result);
结果:{ie: "utf8", query: "呵呵", pid: "AQKo5-0000"}
3.escape unescape
ECMAScript v3 已从标准中删除了 escape unescape函数,并反对使用它,因此应该用 decodeURI() 和 decodeURIComponent() 取而代之。
URI方法能编码素所有Unicode字符,而 escape unescape只能正确编码ASCLL字符,可以看下面的demo,编码结果有点不伦不类,不便于使用:
var str = 'https://www.baidu.com/s?tn=mswin_oem_dg&ie=utf-16&word=hello';
escape(str) //https%3A//www.baidu.com/s%3Ftn%3Dmswin_oem_dg%26ie%3Dutf-16%26word%3Dhello