函數 | 描述 |
encodeURI() | 把字符串編碼為 URI |
encodeURIComponent() | 把字符串編碼為 URI 組件 |
escape() | 對字符串進行編碼 |
上面是查詢來自w3school的資料。那么三者之間有什么區別呢,請容我測試測試。
var str = "http://localhost:8080/Product/index?id=123&attr=456&area=中國"; console.log(encodeURI(str)); console.log(encodeURIComponent(str)); console.log(escape(str));
打印結果如下:
http://localhost:8080/Product/index?id=123&attr=456&area=%E4%B8%AD%E5%9B%BD http%3A%2F%2Flocalhost%3A8080%2FProduct%2Findex%3Fid%3D123%26attr%3D456%26area%3D%E4%B8%AD%E5%9B%BD http%3A//localhost%3A8080/Product/index%3Fid%3D123%26attr%3D456%26area%3D%u4E2D%u56FD
可以看出,
encodeURI不會對:/?&= 這幾個在uri中起分割作用的字符進行編碼;
encodeURIComponent則會相應的編碼成%3A、%2F、%3F、%26、%3D。
觀察escape則發現,:?&都被轉碼了,而/沒有,w3school解釋是,escape函數會對ascii碼中字母、數字及符號( * @ - _ + . / )之外的所有字符進行編碼。
另外,我們可以看出escape對漢字“中國”編碼后結果與前兩者不同。W3SCHOOL也建議不使用該方法,用前兩者代替。