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 進行解碼。
var m = decodeURIComponent("https%3A%2F%2Fbaidu.com%2Fa(-_.!~*')1"); console.log(m); // "https://baidu.com/a(-_.!~*')1"
4、decodeURI 可對 encodeURI編碼的 URI 進行解碼。
var n = decodeURI("%E4%B8%AD%E5%9B%BDhttps://www.baidu.com/;,/?:@&=+$a2-_.!~*'()#"); console.log(n); //"中國https://www.baidu.com/;,/?:@&=+$a2-_.!~*'()#"
5、運用:取地址欄中文參數亂碼
send.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> <title>send</title> </head> <body> </body> <script type="text/javascript" charset="utf-8"> //window.location.href = 'reception.html?p=廣東&c=廣州' window.location.href = 'reception.html?p=%E5%B9%BF%E4%B8%9C&c=%E5%B9%BF%E5%B7%9E' </script> </html>
reception.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> <title>reception</title> </head> <body> </body> <script type="text/javascript" charset="utf-8"> /* * 取地址欄的參數 * @param key * key為傳遞的參數名稱 例如 reception.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; } // 控制台打印參數 p console.log(getUrlParam('p')); // 結果為 廣東 // 控制台打印參數 c console.log(getUrlParam('c')); // 結果為 廣州 </script> </html>