获取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