获取url的参数

时间:2019-02-14 11:53:06   收藏:0   阅读:215

工作中封装了一些通用的公共方法,最常见的就属在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

原文:https://www.cnblogs.com/Richard-M/p/10373711.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!