一、獲取瀏覽器參數(shù)方法
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] || "";
}
說(shuō)明:
1、window.location.search:是獲取URL地址的查詢部分 eg: " ?name=dingFY&age=18 "
2、window.location.search.replace(/^?/, ""):去掉查詢部分的 " ? "
3、search.split("&"): 將查詢部分字符串以&為分界切割成數(shù)組
4、遍歷數(shù)組,將數(shù)組的每一項(xiàng)以=為分界進(jìn)行切割保存為鍵值對(duì),對(duì)鍵和值進(jìn)行URL解碼,再合成為對(duì)象
5、從對(duì)象中返回用戶指定key鍵的value值
二、decodeURIComponent()函數(shù)
decodeURIComponent() 函數(shù)可對(duì) encodeURIComponent() 函數(shù)編碼的 URI 進(jìn)行解碼。
語(yǔ)法:decodeURIComponent(URIstring)
參數(shù):URIstring:必需,一個(gè)字符串,含有編碼 URI 組件或其他要解碼的文本。
返回值:URIstring 的副本,其中的十六進(jìn)制轉(zhuǎn)義序列將被它們表示的字符替換。
舉例:
let tast="http://www.baidu.com/My first/"
document.write(encodeURIComponent(test)+ "<br />")
document.write(decodeURIComponent(test))
// 頁(yè)面輸出:
// http%3A%2F%2Fwww.baidu.com%2FMy%20first%2F
// http://www.baidu.com/My first/
三、舉例
假設(shè)當(dāng)前頁(yè)面的URL為:
調(diào)用getParams()方法獲取organizeCode的參數(shù)值
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
}
文章每周持續(xù)更新,可以微信搜索「 前端大集錦 」第一時(shí)間閱讀,回復(fù)【視頻】【書籍】領(lǐng)取200G視頻資料和30本PDF書籍資料