字符转码(escape()、encodeURI()、encodeURIComponent()区别详解)

escape()

escape() 函数可对字符串进行编码,这样就可以在所有的计算机上读取该字符串。

返回值:已编码的 string 的副本。其中某些字符被替换成了十六进制的转义序列。
解码: unescape() (ECMAScript v3 已从标准中删除unescape()函数,并反对使用它,因此应该用 decodeURI()decodeURIComponent() 取而代之。)

escape(string)  // string 必需。要被转义或编码的字符串

document.write(escape("Visit W3School!") + "
") // Visit%20W3School%21 document.write(escape("李果然")+ "
") // %u674E%u679C%u7136 document.write(escape("?!=()#%&")) // %3F%21%3D%28%29%23%25%26

说明:该方法不会对 ASCII 字母和数字进行编码,也不会对下面这些 ASCII 标点符号进行编码: * @ - _ + . / 。其他所有的字符都会被转义序列替换

encodeURI()

encodeURI() 函数可把字符串作为 URI 进行编码。

返回值: URIstring 的副本,其中的某些字符将被十六进制的转义序列进行替换。
提示:如果 URI 组件中含有分隔符,比如 ? 和 #,则应当使用 encodeURIComponent()方法分别对各组件进行编码。

encodeURI(URIstring)  // 必需。一个字符串,含有 URI 或其他要编码的文本。

document.write(encodeURI("http://www.w3school.com.cn")+ "
") // http://www.w3school.com.cn document.write(encodeURI("李果然")) // %E6%9D%8E%E6%9E%9C%E7%84%B6 document.write(encodeURI("http://www.w3school.com.cn/My first/")) // http://www.w3school.com.cn/My%20first/ document.write(encodeURI(",/?:@&=+$#")) // ,/?:@&=+$#

说明:该方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ * ' ( ) 。
该方法的目的是对 URI 进行完整的编码,因此对以下在 URI 中具有特殊含义的 ASCII 标点符号,encodeURI() 函数是不会进行转义的:;/?:@&=+$,#

encodeURIComponent()

encodeURIComponent() 函数可把字符串作为 URI 组件进行编码。

返回值: URIstring 的副本,其中的某些字符将被十六进制的转义序列进行替换。
说明: 该方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ * ' ( ) 。
其他字符(比如 :;/?:@&=+$,# 这些用于分隔 URI 组件的标点符号),都是由一个或多个十六进制的转义序列替换的。

提示:请注意 encodeURIComponent() 函数 与 encodeURI()函数的区别之处,前者假定它的参数是 URI 的一部分(比如协议、主机名、路径或查询字符串)。因此 encodeURIComponent()函数将转义用于分隔 URI 各个部分的标点符号。

encodeURIComponent(URIstring)   // URIstring 必需。一个字符串,含有 URI 组件或其他要编码的文本。

document.write(encodeURIComponent("http://www.w3school.com.cn"))    // http%3A%2F%2Fwww.w3school.com.cn
document.write(encodeURIComponent("http://www.w3school.com.cn/p 1/"))  // http%3A%2F%2Fwww.w3school.com.cn%2Fp%201%2F
document.write(encodeURIComponent(",/?:@&=+$#"))   // %2C%2F%3F%3A%40%26%3D%2B%24%23
document.write(encodeURIComponent("李果然"))  // %E6%9D%8E%E6%9E%9C%E7%84%B6

你可能感兴趣的:(字符转码(escape()、encodeURI()、encodeURIComponent()区别详解))