1. encodeURIComponent() 函數(shù)可把字符串作為 URI 組件進行編碼蜻韭。
encodeURIComponent('周圣楠') // "%E5%91%A8%E5%9C%A3%E6%A5%A0"
2. decodeURIComponent() 函數(shù)可對 encodeURIComponent() 函數(shù)編碼的 URI 進行解碼
decodeURIComponent('%E5%91%A8%E5%9C%A3%E6%A5%A0') // "周圣楠"
3. encodeURI() 作用和 encodeURIComponent() 類似悼尾,但他們編碼的范圍有區(qū)別:
3.1 encodeURI()方法不會對下列字符編碼:ASCII字母、數(shù)字湘捎、~!@#$&*()=:/,;?+'
3.2 encodeURIComponent()方法不會對下列字符編碼:ASCII字母诀豁、數(shù)字、~!*()'
3.3 二者都會對中文進行編碼
一般來說窥妇,在編碼范圍內(nèi)舷胜,encodeURI() 和 encodeURIComponent() 編碼后的結(jié)果是一樣:
encodeURI('周圣楠') // "%E5%91%A8%E5%9C%A3%E6%A5%A0"
encodeURIComponent('周圣楠') // "%E5%91%A8%E5%9C%A3%E6%A5%A0"
3.3 使用場景的區(qū)別:對 整個URL
進行編碼就使用 encodeURI(),對 URL中的參數(shù)
或者 URL后面的一部分
進行編碼就使用 encodeURIComponent()
使用 encodeURI() 只將空格編碼成 20%
encodeURI('http://tieba.baidu.com/?name=zhou value') // "http://tieba.baidu.com/?name=zhou%20value"
使用 encodeURIComponent() 對整個 URL編碼可能會導(dǎo)致URL失效(不僅編碼了空格活翩,還編碼了 // ):
encodeURIComponent('http://tieba.baidu.com?name=zhou value') // "http%3A%2F%2Ftieba.baidu.com%3Fname%3Dzhou%20value"
因此一般情況下烹骨,如果我們只需對 URL 后面的參數(shù)進行編碼的話,使用 encodeURIComponent() 編碼參數(shù)后材泄,再拼接到 URL 后面去