首页 > Web开发 > 详细

获取url的参数

时间:2019-02-14 11:53:06      阅读:215      评论:0      收藏:0      [点我收藏+]

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

获取url的参数

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!