面試官問:如何拆解URL參數(shù)中queryString
入?yún)⒏袷絽⒖迹?/strong>
const url = 'http://sample.com/?a=1&b=2&c=xx&d=2#hash';
出參格式參考:
const result = { a: '1', b: '2', c: 'xx', d: '' };
// 拆解URL參數(shù)中queryString,返回一個 key - value 形式的 object解答一:正則
const queryString = (str)=>{
const obj = {}
str.replace(/([^?&=]+)=([^&]+)/g, (_, k, v) => (obj[k] = v))
return obj
}
解答二:URLSearchParams
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))
解答三:字符串分割
字符串分割拿到參數(shù)相關(guān)的字符串,再做類型轉(zhuǎn)換
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;
}
公眾號內(nèi)回復(fù)【正則】
免費領(lǐng)取【JavaScript 正則表達式迷你書.pdf】
來源:https://github.com/sisterAn/JavaScript-Algorithms
最后
評論
圖片
表情
