Open DarkFlame opened 6 years ago
三者都对字符串进行编码
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*_+-./ escape('abc123'); // "abc123" escape('@*_+-./'); // "@*_+-./"
Encode(uriString, unescapedSet),区别在于unescapedSet的集合不一样
encodeURI的unescapedSet是
#
encodeURLComponent的unescapedSet是
uriUnescaped
现在看看ECMAScript规范中对 uriReserved ,uriUnescaped 的定义
uri :::(uri的基本组成单元是 uriCharacters,每个 uriCharacters 由 uriCharacter 组成) uriCharacters uriCharacters ::: uriCharacter uriCharacter uriCharacter ::: (一个 uriCharacter 由 uriReserved【uri保留字】,uriUnescaped【uri不需要编码的】 ,uriEscaped【uri中需要编码的】) uriReserved uriUnescaped uriEscaped uriReserved ::: one of ; / ? : @ & = + $ , uriUnescaped ::: uriAlpha (字母) DecimalDigit (数字) uriMark 【- _ . ! ~ * ' ( ) 这几个字符】
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
_ . ! ~ * ' ( )
encodeURI函数的目的是使用完整的URI;他们假定URI中的任何 uriReserved 单元都具有特殊的含义,因此没有进行编码。 encodeURIComponent函数用于处理URI的各个组件部分;它们假定任何保留的 uriReserved 单元都表示文本, 因此必须对它们进行编码,以便当组件是完整URI的一部分时,不会将它们视为为 uriReserved 单元。 综上总结如下 encodeURI 对除了以下的进行编码 - ; / ? : @ & = + $ - \# - 字母 - 数字 - \- _ . ! ~ * ' ( ) 综上总结如下 encodeURIComponent 对除了以下的进行编码 - 字母 - 数字 - \- _ . ! ~ * ' ( ) ### 最后再来看一demo
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)
escape()和encodeURI()和encodeURLComponent()的具体区别
三者都对字符串进行编码
escape()是一个通用函数,对除下面之外的编码
encodeURI 和 encodeURLComponent 用于对uri用途的字符串进行编码,二者在底层都是调用
Encode(uriString, unescapedSet),区别在于unescapedSet的集合不一样
encodeURI的unescapedSet是
#
encodeURLComponent的unescapedSet是
uriUnescaped
现在看看ECMAScript规范中对 uriReserved ,uriUnescaped 的定义
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)