獲取url的參數


工作中封裝了一些通用的公共方法,最常見的就屬在url上拿參數了

現在用的是 getUrlParam2 方法


/**
* 瀏覽器里取參數
* @param name
* @returns {*}
*/
export function getUrlParam(search, name) {
const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, 'i');
const r = search.substr(1).match(reg);
if (r != null) return decodeURI(r[2]);
return null;
}

/**
* 瀏覽器里取參數
* @param name
* @returns {string}
*/
export function getUrlParam2(name) {
let urlArr = window.location.href.split('?');
if (urlArr.length < 2) {
return '';
}
let tempArr = urlArr[1].split('&');
for (let i = 0; i < tempArr.length; i++) {
let item = tempArr[i].split('=');
if (item[0].trim() == name) {
return item[1];
}
}
return '';
}
 
小擴展:
如何檢測

location.href 整個url地址

location.protocol 獲取協議

location.pathname 獲取地址

location.search 獲取?后面的參數

location.hash 獲取哈希

 

如:

http://www.baidu.com/class.html?aa=1&bb==2#id=123

location.href           http://www.baidu.com/class.html?aa=1&bb==2#id=123

location.host          www.baidu.com

location.protocol     http://

location.pathname   /class.htm

location.search       ?aa=1&bb==2

location.hash          #id=123


免責聲明!

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



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