URI 方法 encodeURI() encodeURIComponent() docodeURI() decodeURIComponent()

时间:2023-03-09 03:50:39
URI 方法 encodeURI() encodeURIComponent() docodeURI() decodeURIComponent()

URI 方法  encodeURI()  encodeURIComponent()  docodeURI()  decodeURIComponent()

var sUri = “http://www.wrox.com/illegal value.htm#start”;
alert(encodeURI(sUri));   
alert(encodeURIComponent(sUri))
输出
http://www.wrox.com/illegal%20value.htm#start
http%3A%2F%2Fwww.wrox.com%2Fillegal%20value.htm%23start
var sUri = “http%3A%2F%2Fwww.wrox.com%2Fillegal%20value.htm%23start”;
alert(decodeURI(sUri));
alert(decodeURIComponent(sUri));
输出
http%3A%2F%2Fwww.wrox.com%2Fillegal value.htm%23start
http://www.wrox.com/illegal value.htm#start
encodeURI()
该方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ * ' ( ) 。
该方法的目的是对 URI 进行完整的编码,因此对以下在 URI 中具有特殊含义的 ASCII 标点符号,encodeURI() 函数是不会进行转义的:;/?:@&=+$,#
encodeURIComponent()
该方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ * ' ( ) 。
其他字符(比如 :;/?:@&=+$,# 这些用于分隔 URI 组件的标点符号),都是由一个或多个十六进制的转义序列替换
URI 方法比BOM 方法 escape()   unescape()  要好
通过对三个函数的分析,我们可以知道:escape()除了 ASCII 字母、数字和特定的符号外,对传进来的字符串全部进行转义编码,因此如果想对URL编码,最好不要使用此方法。而encodeURI() 用于编码整个URI,因为URI中的合法字符都不会被编码转换。encodeURIComponent方法在编码单个URIComponent(指请求参数)应当是最常用的,它可以讲参数中的中文、特殊字符进行转义,而不会影响整个URL。
The URI methods are always preferable because they encode all Unicode characters,whereas the BOM methods encode only ASCII characters correctly. Avoid using  escape() and  unescape()