url/urlParamToObj.jsjavascript
/**
* 将 URL 查询字符串转换为对象。重复参数保留为数组,单值参数保留为字符串。
* @function urlParamToObj
* @memberof module:url
* @param {string} url 要解析的 URL 字符串
* @returns {Record<string, string | string[]>} 查询参数对象
* @throws {TypeError} url 不是字符串时抛出
*/
function urlParamToObj(url) {
if (typeof url !== 'string') {
throw new TypeError('url must be a string')
}
const queryStart = url.indexOf('?')
if (queryStart === -1) return {}
const hashStart = url.indexOf('#', queryStart)
const query = url.slice(queryStart, hashStart === -1 ? undefined : hashStart)
const sp = new URLSearchParams(query)
const obj = {}
for (const [key, value] of sp.entries()) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
obj[key] = Array.isArray(obj[key]) ? [...obj[key], value] : [obj[key], value]
} else {
obj[key] = value
}
}
return obj
}
export default urlParamToObj