- url参数解析为对象
- url参数解析为数组
- URLSearchParams(兼容性有待提高,慎用)
url参数解析为对象
const urlQueryToObject = (url) => {
if((/\?/).test(url)) {
const arr = url.split('?')[1].split('&');
return arr.reduce((acc,value,index) => {value.replace(/(\w+)=(\w+)/,(match,p1,p2) => {acc[p1] = p2});return acc},{});
}
return {}
}
const getURLParameters = url =>
(url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
(a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
{}
);
// example
// location.href ='http://example.com/user?id=1&age=2'
const paramsObj = urlQueryToObject(location.href) //{id: "1", age: "2"}
paramsObj.id
paramsObj.age
url参数解析为数组
const urlQueryToArr = url => {
if((/\?/).test(url)) {
const arr = url.split('?')[1].split('&');
return arr.reduce((acc,value,index) => {acc.push(value.split('='));return acc;},[])
}
return []
}
// example
// location.href ='http://example.com/user?id=1&age=2'
JSON.stringify(urlQueryToArr(location.href)) // "[["id","1"],["age","2"]]"
URLSearchParams
/**
*
* @param {string} url
* @return URLSearchParams ;
*/
const urlParams = url => {
if(/\?/.test(url)) {
return searchParams = new URLSearchParams( url.split('?')[1]);
}
return new URLSearchParams()
}
useage
// location.href ='http://example.com/user?id=1&age=2'
const params = urlParams(location.href); //iterater obj
params.get('id') // 1
params.has('id') // true
params.append('id','2')
params.getAll('id') // ?["1", "2"]
params.set('id','0')
params.get('id') // "0"
params.getAll('id') // ["0"]
params.delete('id')
params.get('id') // null
params.toString() //"age=2"
references:
原文地址:https://www.cnblogs.com/rosendolu/p/11623065.html
时间: 2024-10-07 09:38:12