字符串编码

之前对url进行编码的时候遇到过encodeURI和encodeURIComponent,如今要设置cookie的value又遇到了escape(),并且提示说,尽量不用这个方法。

那么这些方法有什么区别呢?

escape

首先这个方法被不推荐使用。如上图所示。

它不会对ASCII字母 数字 * @ - _ + . /这些符号进行转义。

下面这张table表示了escape方法对哪些字符进行编码:

下面这张table表示了escape方法对哪些字符不进行编码:

encodeURI

下面内容部分来自于知乎答案:黄家兴的回答

他用来对完整的url编码。它不会对:ASCII字母 数字 ~ ! @ # $ & * ( ) = : / , ; ? + ‘ 这些符号进行转义。

1
2
3
4
encodeURI("http://www.cnblogs.com/season-huang/some other thing");

//result
"http://www.cnblogs.com/season-huang/some%20other%20thing";

其中,空格被编码成了%20。但是如果你用了encodeURIComponent,那么结果变为

1
"http%3A%2F%2Fwww.cnblogs.com%2Fseason-huang%2Fsome%20other%20thing"

看到了区别吗,连 “/“ 都被编码了,整个URL已经没法用了。

下面这张table表示了encodeURI方法对哪些字符进行编码:

下面这张table表示了encodeURI方法对哪些字符不进行编码:

encodeURIComponent

他用来对url的部分query参数进行编码。它不会对ASCII字母 数字 ~ ! * ( ) ‘这些符号进行转义。

1
2
3
4
var param = "http://www.cnblogs.com/season-huang/"; //param为参数
param = encodeURIComponent(param);
var url = "http://www.cnblogs.com?next=" + param;
console.log(url) //"http://www.cnblogs.com?next=http%3A%2F%2Fwww.cnblogs.com%2Fseason-huang%2F"

下面这张table表示了encodeURIComponent方法对哪些字符进行编码:

下面这张table表示了encodeURIComponent方法对哪些字符不进行编码:

总结

escape不推荐使用

encodeURIComponent会毁掉整个url,他只适用于当一个url是另一个url的参数时,对其进行编码

encodeURI可以对完整的url进行编码。

题外话

这些数据是我用一下代码生成的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
var arr1 = [];
var arr2 = [];
var arr3 = [];
var arr4 = [];
var arr5 = [];
var arr6 = [];
for (var i = 0; i < 127; i++) {
var char = String.fromCharCode(i);
if (encodeURI(char) == char) {
arr1.push({
charcode: i,
character: char,
encodeURI: encodeURI(char),
});
}
if (encodeURI(char) !== char) {
arr2.push({
charcode: i,
character: char,
encodeURI: encodeURI(char),
});
}
if (escape(char) == char) {
arr3.push({
charcode: i,
character: char,
escape: escape(char),
});
}
if (escape(char) !== char) {
arr4.push({
charcode: i,
character: char,
escape: escape(char),
});
}
if (encodeURIComponent(char) == char) {
arr5.push({
charcode: i,
character: char,
encodeURIComponent: encodeURIComponent(char),
});
}
if (encodeURIComponent(char) !== char) {
arr6.push({
charcode: i,
character: char,
encodeURIComponent: encodeURIComponent(char),
});
}
}

然后用console.table(arr1)就可以在控制台打印了。

然而console.table这么方便有木有可以直接把array转成table的api,直接显示在网页上?上网找了一下貌似不太可心。而且这么基础的程序我希望能用原生js实现。so,做了个轮子,把array转成table。基本实现了console.table的用法。传送门