1. 程式人生 > >encodeURI() encodeURIComponent()

encodeURI() encodeURIComponent()

URI: Uniform Resource Identifiers,通用資源識別符號

Global物件的encodeURI()和encodeURIComponent()方法可以對URI進行編碼,以便傳送給瀏覽器。

有效的URI中不能包含某些字元,例如空格。而這URI編碼方法就可以對URI進行編碼,它們用特殊的UTF-8編碼替換所有無效的字 符,從而讓瀏覽器能夠接受和理解。

編碼

encodeURI()   對整個URI編碼          (例如,http://www.jxbh.cn/illegal value.htm)

encodeURIComponent()    對URI中的某一段編碼   

         (例如前面URI中的illegal value.htm)

解碼

decodeURIComponent()

區別:

encodeURI()不會對本身屬於URI的特殊字元進行編碼,例如冒號、正斜槓、問號 、#;

encodeURIComponent()則會對任何非標準字元進行編碼。來看下面的例子:

var uri="http://www.jxbh.cn/illegal value.htm#start"; encodeURI (uri)       //     ”http: //www.jxbh.cn/illegal%20value .htm#start” encodaURIComponent (uri);   //       ”http% 3A%2F%2F

www.jxbh.cn%2 Fillegal%2 0value. htm%23 start”

一般來說,我們使用encodeURIComponent()方法的時候要比使用encodeURI()更多,因為在實踐中更常見的是對查詢字串引數而不是對基礎URL進行編碼.