- 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:數組