encodeURI(),encodeURIComponent()使用場景


URI:(Uniform Resource Identifier)統一資源標識符

URL:(Uniform Resource Locator)統一資源定位符:不僅標識了Web 資源,還指定了操作或者獲取方式,同時指出了主要訪問機制和網絡位置。

URN:(Uniform Resource Name)統一資源名稱:用特定命名空間的名字標識資源。使用URN可以在不知道其網絡位置及訪問方式的情況下討論資源。

URI可以被分為URL、URN或兩者的組合。

案例:

  這是一個URI:http://bitpoetry.io/posts/hello.html#intro

  http:// 是定義如何訪問資源的方式;bitpoetry.io/posts/hello.html 是資源存放的位置;#intro 是資源。

  URL是URI的一個子集:告訴我們訪問網絡位置的方式。在我們的例子中,URL應該為:http://bitpoetry.io/posts/hello.html

  URN是URI的一個子集,包括名字(給定的命名空間內),但是不包括訪問方式,應該為:bitpoetry.io/posts/hello.html#intro

相同:

encodeURIComponent()和 encodeURI()都是對 URI 進行編碼。

解碼:

  encodeURIComponent() <=>  decodeURIComponent()

  encodeURI() <=>    decodeURI()

不同:

encodeURIComponent() 不轉義的字符:A-Z a-z 0-9 - _ . ! ~ * ' ( )

encodeURI():只對空格進行轉義

var set1 = ";,/?:@&=+$";  // 保留字符
var set2 = "-_.!~*'()";   // 不轉義字符
var set3 = "#";           // 數字標志
var set4 = "ABC abc 123"; // 字母數字字符和空格

console.log(encodeURI(set1)); // ;,/?:@&=+$
console.log(encodeURI(set2)); // -_.!~*'()
console.log(encodeURI(set3)); // #
console.log(encodeURI(set4)); // ABC%20abc%20123 (the space gets encoded as %20)

console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24
console.log(encodeURIComponent(set2)); // -_.!~*'()
console.log(encodeURIComponent(set3)); // %23
console.log(encodeURIComponent(set4)); // ABC%20abc%20123 (the space gets encoded as %20)

 

使用場景:

  1、encodeURI:適用於url跳轉時。

  2、encodeURIComponent:適用於url作為參數傳遞時,對參數解碼。

   http://www.我.com?a=? 想把?傳給服務器
encodeURI('http://www.我.com?a=?')   // "http://www.%E6%88%91.com?a=?"
服務器收到的a值為空,因為?是URL保留字符。此時我們需要用encodeURIComponent來編碼!
 
encodeURIComponent會編碼所有的URL保留字,所以不適合編碼URL。如:當我們把編碼過的/folder1/folder2/default.html發送到服務器時時,由於‘/’也將被編碼,服務器將無法正確識別。
encodeURIComponent('http://www.我.com') //"http%3A%2F%2Fwww.%E6%88%91.com"
 
encodeURI('http://www.我.com') + '?a=' + encodeURIComponent('?');   

 

 

參考:

https://blog.csdn.net/f45056231p/article/details/82530984

https://www.cnblogs.com/shytong/p/5102256.html

    

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM