DarkFlame / blog

blog for me
2 stars 0 forks source link

escape()和encodeURI()和encodeURLComponent()的具体区别 #12

Open DarkFlame opened 6 years ago

DarkFlame commented 6 years ago

escape()和encodeURI()和encodeURLComponent()的具体区别

三者都对字符串进行编码

escape()是一个通用函数,对除下面之外的编码

  ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*_+-./
  escape('abc123');     // "abc123"
  escape('@*_+-./');    // "@*_+-./"

encodeURI 和 encodeURLComponent 用于对uri用途的字符串进行编码,二者在底层都是调用

Encode(uriString, unescapedSet),区别在于unescapedSet的集合不一样

encodeURI的unescapedSet是

uriAlpha ::: one of a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

uriMark ::: one of

var set1 = ";,/?:@&=+$#"; // uriReserved var set2 = "-_.!~*'()"; // uriUnescaped 中的 uriMark var set3 = "ABC abc 123"; // uriUnescaped 中的 uriAlpha 和 DecimalDigit + Space

console.log(encodeURI(set1)); // ;,/?:@&=+$# console.log(encodeURI(set2)); // -_.!~*'() console.log(encodeURI(set3)); // ABC%20abc%20123 (空格被编码成 %20)

console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24%23 console.log(encodeURIComponent(set2)); // -_.!~*'() console.log(encodeURIComponent(set3)); // ABC%20abc%20123 (空格被编码成 %20)