function getParams(key) {
let search = window.location.search.replace(/^\?/, "");
let pairs = search.split("&");
let paramsMap = pairs.map(pair => {
let [key, value] = pair.split("=");
return [decodeURIComponent(key), decodeURIComponent(value)];
}).reduce((res, [key, value]) => Object.assign(res, { [key]: value }), {});
return paramsMap[key] || "";
}複製代碼
說明:javascript
一、window.location.search:是獲取URL地址的查詢部分 eg: " ?name=dingFY&age=18 "html
二、window.location.search.replace(/^\?/, ""):去掉查詢部分的 " ? "java
三、search.split("&"): 將查詢部分字符串以&爲分界切割成數組數組
四、遍歷數組,將數組的每一項以=爲分界進行切割保存爲鍵值對,對鍵和值進行URL解碼,再合成爲對象瀏覽器
五、從對象中返回用戶指定key鍵的value值函數
decodeURIComponent() 函數可對 encodeURIComponent() 函數編碼的 URI 進行解碼。ui
語法: decodeURIComponent(URIstring)編碼
參數:URIstring:必需,一個字符串,含有編碼 URI 組件或其餘要解碼的文本。spa
返回值:URIstring 的副本,其中的十六進制轉義序列將被它們表示的字符替換。code
舉例:
let tast="http://www.baidu.com/My first/"
document.write(encodeURIComponent(test)+ "<br />")
document.write(decodeURIComponent(test))
// 頁面輸出:
// http%3A%2F%2Fwww.baidu.com%2FMy%20first%2F
// http://www.baidu.com/My first/複製代碼
假設當前頁面的URL爲:
調用getParams()方法獲取organizeCode的參數值
function getParams(organizeCode) {
let search = window.location.search.replace(/^\?/, "");
// organizeCode=44030022&organizeName=%22%E9%BB%84%E5%9F%94%E7%9C%8B%E5%AE%88%E6%89%80%22
let pairs = search.split("&");
// ["organizeCode=44030022", "organizeName=%22%E9%BB%84%E5%9F%94%E7%9C%8B%E5%AE%88%E6%89%80%22"]
let paramsMap = pairs.map(pair => {
let [key, value] = pair.split("=");
return [decodeURIComponent(key), decodeURIComponent(value)];
}).reduce((res, [key, value]) => Object.assign(res, { [key]: value }), {});
// {organizeCode: "44030022", organizeName: ""黃埔看守所""}
return paramsMap[organizeCode] || "";
// 44030022
}複製代碼