标签:parameter cat delete ons new amp value query href
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
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"]]"
/**
*
* @param {string} url
* @return URLSearchParams ;
*/
const urlParams = url => {
if(/\?/.test(url)) {
return searchParams = new URLSearchParams( url.split('?')[1]);
}
return new URLSearchParams()
}
// 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:
标签:parameter cat delete ons new amp value query href
原文地址:https://www.cnblogs.com/rosendolu/p/11623065.html