Daily-Question
Daily-Question copied to clipboard
【Q429】实现一个函数用来解析 URL 的 querystring
示例,如
const url = 'https://shanyue.tech?a=3&b=4&c=5'
// 解析后得到 qs 如下
const qs = {
a: 3,
b: 4,
c: 5
}
关于路由中解析 querystring,无论前端开发还是后端开发都无时无刻在使用这项功能,即使几乎没有人手动解析过它。这里来实现一个简单粗暴的解析函数
- 如何使用正则解析 qs
- 如何正确转义汉字
- 如何正确处理数组
- 如何处理各种复杂的嵌套对象
关于如何实现复杂嵌套对象,边界条件过多,强烈推荐一个 npm 库 qs
为此总结出以下用例用以检查解析函数的正确性
// {}
'https://shanyue.tech'
// {a: ''}
'https://shanyue.tech?a'
// {name: '山月'}
'https://shanyue.tech?name=%E5%B1%B1%E6%9C%88'
// {name: '山月', a: 3}
'https://shanyue.tech?name=%E5%B1%B1%E6%9C%88&a=3'
// {name: '山月', a: [3, 4]}
'https://shanyue.tech?name=%E5%B1%B1%E6%9C%88&a=3&a=4'
// {name: '山月', a: 3}
'https://shanyue.tech?name=%E5%B1%B1%E6%9C%88&a=3#hash'
// {name: '1+1=2'}
'https://shanyue.tech?name=1%2B1%3D2'
纯碎使用 javascript
完成解析函数,而不利用浏览器 DOM 特性 API,代码如下所示,细节在注释中体现
function parse(url) {
// 一、夹杂在 ? 与 # 之前的字符就是 qs,使用 /\?([^/?#:]+)#?/ 正则来抽取
// 使用正则从 URL 中解析出 querystring
// 二、通过 Optional Chain 来避免空值错误
const queryString = url.match(/\?([^/?#:]+)#?/)?.[1]
if (!queryString) { return {} }
queryObj = queryString.split('&').reduce((params, block) => {
// 三、如果未赋值,则默认为空字符串
const [_k, _v = ''] = block.split('=')
// 四、通过 decodeURIComponent 来转义字符,切记不可出现在最开头,以防 ?tag=test&title=1%2B1%3D2 出错
const k = decodeURIComponent(_k)
const v = decodeURIComponent(_v)
if (params[k] !== undefined) {
// 处理 key 出现多次的情况,设置为数组
params[k] = [].concat(params[k], v)
} else {
params[k] = v
}
return params
}, {})
return queryObj
}
如果引入浏览器特性 API,问题就简单很多迎刃而解,所涉及到的 API 有两个,这里不做展开
-
new URL(url)
-
new URLSearchParams(paramsString)
一开始decodeURIComponent(url)
是否不妥,如果query string中的value带有=
等字符并且已经被encodeURIComponent
,如http://example.com?tag=test&title=1%2B1%3D2
中title=1+1=2
,使用parse解析的结果是错误的。使用params[k] = decodeURIComponent(v)
是不是更好
@ly023 感谢老哥指正
function url2Params(url) {
const dict = {};
url.replace(/([^?&]*)=([^&]*)/g, (__, key, val) => {
key = decodeURIComponent(key);
val = decodeURIComponent(val);
if (dict[key]) return (dict[key] = [dict[key], val].flat());
dict[key] = val;
});
return dict;
}
使用 URLSearchParams
function parse() {
let serach = window.location.search
let params = new URLSearchParams(serach),queryObj={}
for(let [k,v] of params.entries()){
if(queryObj[k]!==undefined){
queryObj[k] = [].concat(queryObj[k],v)
}else{
queryObj[k] = v
}
}
return queryObj
}
function qsParse(url = '') {
const params = {};
if (url.includes('?')) {
let startIndex = url.indexOf('?');
if (startIndex !== -1) {
url = url.slice(startIndex + 1);
}
}
const pairs = url.split('&');
for (let pair of pairs) {
const [key, value] = pair.split('=');
const decodeKey = decodeURIComponent(key);
const decodeValue = decodeURIComponent(value);
if (params.hasOwnProperty(decodeKey)) {
if (Array.isArray(params[decodeKey])) {
params[decodeKey].push(decodeValue);
} else {
params[decodeKey] = [params[decodeKey], decodeValue];
}
} else {
params[decodeKey] = decodeValue;
}
}
return params;
}