从URL查询字符串中提取键值对的多种方法
// 方法一:使用 URLSearchParams
/**
* 从URL或路径中提取查询参数
* @param {string} input - 完整URL或路径字符串
* @returns {object} - 解析后的查询参数对象
*/
function queryParse(input = '/frameworkPlan/frameworkPlanList?a=1&b=2') {
// 输入验证
if (!input || typeof input !== 'string') {
return {}
}
const url = new URL(path, 'https://bidchina.cn/#/login') // 第二个参数为基础 URL,用于解析相对路径
// const url = new URL(path, window.location.href);
const params = new URLSearchParams(url.search)
// 获取所有参数
const queryObj = Object.fromEntries(params.entries())
// 单独获取某个参数
console.log(params.get('a')) // 输出: '1'
console.log(queryObj) // 输出: { a: '1', b: '2' }
return queryObj
}
// 方法二:手动解析查询字符串
/**
* 从URL或路径中提取查询参数
* @param {string} input - 完整URL或路径字符串
* @returns {object} - 解析后的查询参数对象
*/
function parseQueryString(input) {
// 输入验证
if (!input || typeof input !== 'string') {
return {}
}
// 提取查询字符串部分
const queryStartIndex = input.indexOf('?')
if (queryStartIndex === -1) {
return {} // 没有查询字符串
}
const queryString = input.slice(queryStartIndex + 1)
// 解析查询字符串
const result = {}
if (!queryString) {
return result
}
// 分割参数对并解析
queryString.split('&').forEach((pair) => {
if (!pair) return
// 处理键值对(支持等号缺失的情况,如"?param")
const index = pair.indexOf('=')
let key, value
if (index === -1) {
key = pair
value = ''
} else {
key = pair.slice(0, index)
value = pair.slice(index + 1)
}
// 处理重复参数(转为数组)
if (result[key] !== undefined) {
if (!Array.isArray(result[key])) {
result[key] = [result[key]]
}
result[key].push(value)
} else {
result[key] = value
}
})
return result
}
// 示例使用
const path =
'http://localhost:5173/#/frameworkPlan/frameworkPlanList?a=12&b=112&c=3&c=4'
const path1 = '/frameworkPlan/frameworkPlanList?a=1&b=2&c=3&c=4'
const params = parseQueryString(path)
const params1 = parseQueryString(path1)
console.log(params) // 输出: { a: '1', b: '2', c: ['3', '4'] }
console.log(params1) // 输出: { a: '1', b: '2', c: ['3', '4'] }