Open sisterAn opened 4 years ago
const queryString = (str)=>{
const obj = {}
str.replace(/([^?&=]+)=([^&]+)/g, (_, k, v) => (obj[k] = v))
return obj
}
function getParams(u: URL) {
const s = new URLSearchParams(u.search)
const obj = {}
s.forEach((v, k) => (obj[k] = v))
return obj
}
const url = 'http://sample.com/?a=1&b=2&c=xx&d=2#hash';
getParams(new URL(url))
function getQuery (queryStr) {
const [, query] = queryStr.split('?')
if (query) {
return query.split('&').reduce((pre, cur) => {
const [key, val] = cur.split('=')
pre[key] = decodeURIComponent(val)
return pre
}, {})
}
return {}
}
const parse = (url) => { const l = new URL(url).searchParams; const _params = {}; l.forEach((v,k) => _params[k] = v); return _params }
字符串分割拿到参数相关的字符串,再做类型转换
const dismantle = (url) => {
const aimUrl = url.split('?').pop().split('#').shift().split('&');
const res = {};
aimUrl.forEach(item => {
const [key, val] = item.split('=');
res[key] = val;
});
return res;
}
const parse = (url) => { const l = new URL(url).searchParams; const _params = {}; l.forEach((k,v) => _params[k] = v); return _params }
key 和 val 貌似反了~ @7777sea
const parse = (url) => { const l = new URL(url).searchParams; const _params = {}; l.forEach((k,v) => _params[k] = v); return _params }
key 和 val 貌似反了~ @7777sea
已经修改~
const url = 'http://sample.com/?a=1&b=2&c=xx&d=2#hash';
const queryString = (url) => { let urlStrList = url.split("/?")[1].split('#')[0].split('&') let urlData={}; for (let [index, urlStr] of urlStrList.entries()) { let itemList = urlStr.split('=') urlData[itemList[0]] = decodeURIComponent(itemList[1]) } return urlData } console.log(queryString(url))
@sisterAn 哈喽, 我有个问题,你那个输出的例子为什么要d: '' ? &d=2#hash d不应该是2吗? 还有#hash是啥意思?是因为这个d就要取成空了吗?
const queryString = (url) =>
[...new URL(url).searchParams].reduce((acc, cur) => {
acc[cur[0]] = cur[1];
return acc;
}, {});
/**
* url= url = 'http://sample.com/?a=1&b=2&c=xx&d=2#hash';
*/
//使用URL构造函数 使得url具有searchParams属性
const url = 'http://sample.com/?a=1&b=2&c=xx&d=2#hash';
function getUrlParams(url) {
const urlParams = new URL(url)
const params = urlParams.searchParams
console.log('params: ', params);
const obj = {}
//使用forEach map只能循环数组吗???
params.forEach((item,index)=>obj[index] = item)
return obj
}
console.log(getUrlParams(url))
//使用普通的split map循环
function getUrlParams2(url) {
const indexStart = url.indexOf('?')
const indexEnd = url.indexOf('#')
const params = url.slice(indexStart+1,indexEnd)
let obj = {}
params.split('&').map(item=>{
const objParams = item.split('=')
obj[objParams[0]] = objParams[1]
})
return obj
}
console.log(getUrlParams2(url))
function queryString(url) {
let res = {}
url.replace(/([^?&]+)=([^&#]*)/g, (_, k, v)=>{
res[k] = v
})
return res
}
var url = 'http://sample.com/?a=1&b=2&c=xx&d=#hash'
console.log(queryString(url))
// {a: '1', b: '2', c: 'xx', d: ''}
const getUrlQurey = () => location.search
.slice(1)
.split('&')
.reduce((obj, str) =>
(([k, v]) => ({...obj, [k]: v }) )(str.split('=')),
{})
入参格式参考:
出参格式参考: