1. 程式人生 > >URL編碼解決中文字元亂碼(encodeURIComponent和decodeURIComponent)

URL編碼解決中文字元亂碼(encodeURIComponent和decodeURIComponent)

1、encodeURIComponent 轉義除了字母、數字、(、)、.、!、~、*、'、-和_之外的所有字元(可看下錶的非轉義字元更清晰)。

注意:為了避免伺服器收到不可預知的請求,對任何使用者輸入的作為URI部分的內容你都需要用encodeURIComponent進行轉義。

var x = encodeURIComponent("https://baidu.com/a(-_.!~*')1");

console.log(x);     // "https%3A%2F%2Fbaidu.com%2Fa(-_.!~*')1"

2、encodeURI 會替換所有的字元,但不包括以下字元,即使它們具有適當的UTF-8轉義序列:

注意:encodeURI 自身無法產生能適用於HTTP GET 或 POST 請求的URI,例如對於 XMLHTTPRequests, 因為 "&", "+", 和 "=" 不會被編碼,然而在 GET 和 POST 請求中它們是特殊字元。故因採用encodeURIComponent這個方法會對這些字元編碼。

var y = encodeURI("https://www.baidu.com/;,/?:@&=+$a2-_.!~*'()#");

console.log(y);   //"https://www.baidu.com/;,/?:@&=+$a2-_.!~*'()#"

3、decodeURIComponent 可對 encodeURIComponen編碼的 URI 進行解碼.

     decodeURI 可對 encodeURI編碼的 URI 進行解碼.

運用:取位址列中文引數亂碼

/*
    * 取位址列的引數 
    * @param key  
    * key為傳遞的引數名稱 例如 http://localhost/test.html?p=廣東&c=珠海,key就是p和c 
    * @returns 
*/
function getUrlParam(key){    
// 獲取引數    
var url = window.location.search;    
//window.search 取到的是一串帶引數的字串,如:?p=廣東&c=珠海 

// 正則篩選位址列    
var reg = new RegExp("(^|&)"+ key +"=([^&]*)(&|$)");    
// 匹配目標引數   
var result = url.substr(1).match(reg);    
//返回引數值    
return result ? decodeURIComponent(result[2]) : null;
}

我們需要獲取位址列引數的時候,可以直接呼叫方法getUrlParam(key) 就可以了,並且很好的解決了中文引數的亂碼問題。 

// 控制檯列印引數 p
console.log(getUrlParam('p')); // 結果為 廣東
// 控制檯列印引數 c
console.log(getUrlParam('c')); // 結果為 珠海

window.location 物件所包含的8大屬性:

屬性 描述
hash 從井號 (#) 開始的 URL(錨)
host 主機名和當前 URL 的埠號
hostname 當前 URL 的主機名
href 完整的 URL
pathname 當前 URL 的路徑部分
port 當前 URL 的埠號
protocol 當前 URL 的協議
search 從問號 (?) 開始的 URL(查詢部分)

substr語法:(在字串中抽取從 start 下標開始的指定數目length的字元。第二個引數省略即到結尾)

stringObject.substr(start,length)