url参数操作

1
2
3
4
5
6
7
8
9
10
11
function getQueryString(name) {
if (URLSearchParams) {
// https://developer.mozilla.org/zh-CN/docs/Web/API/URLSearchParams
const params = new URLSearchParams(location.search.replace(/\?/ig, ""));
return params.has(name)? params.get(name) : null
} else {
const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
const r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]); return null;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// https://developer.mozilla.org/zh-CN/docs/Web/API/URLSearchParams
const params = new URLSearchParams(location.search.replace(/\?/ig, ""));
// location.search = "?name=yajun&sex=female"
params.has("yajun"); // true
params.get("sex"); // "female"

/*获取网址参数*/
getQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]); return null;
}

/*获取全部url参数,并转换成json对象*/
getAllQuery (url) {
var url = url ? url : window.location.href;
var _pa = url.substring(url.indexOf('?') + 1),
_arrS = _pa.split('&'),
_rs = {};
for (var i = 0, _len = _arrS.length; i < _len; i++) {
var pos = _arrS[i].indexOf('=');
if (pos == -1) {
continue;
}
var name = _arrS[i].substring(0, pos),
value = window.decodeURIComponent(_arrS[i].substring(pos + 1));
_rs[name] = value;
}
return _rs;
}

/*删除url指定参数,返回url*/
delQuery(url, name){
var baseUrl = url.split('?')[0] + '?';
var query = url.split('?')[1];
if (query.indexOf(name)>-1) {
var obj = {}
var arr = query.split("&");
for (var i = 0; i < arr.length; i++) {
arr[i] = arr[i].split("=");
obj[arr[i][0]] = arr[i][1];
};
delete obj[name];
var url = baseUrl + JSON.stringify(obj).replace(/[\"\{\}]/g,"").replace(/\:/g,"=").replace(/\,/g,"&");
return url
}else{
return url;
}
}
坚持原创技术分享,您的支持将鼓励我继续创作!
  • 本文作者: Leo
  • 本文链接: https://xuebin.me/posts/ea17ae1b.html
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!