JavaScript获取URL中参数值的四种方法

作者:闭包旅人

时间:2026-10-31

浏览:614

本文介绍了在JavaScript中提取URL查询参数的四种常见方式。包括利用现代浏览器支持的URL和URLSearchParams对象、使用正则表达式匹配、通过split与reduce组合拆分,以及基于location.search构建自定义函数。每种方法均附带代码示例与适用场景说明,帮助开发者根据实际需求选择最佳方案。

文章目录

方法1:现代浏览器均支持 URL 和 URLSearchParams 对象,可便捷地从URL中提取参数

// 假设当前URL为 "https://example.com/?name=John&age=30"
const url = new URL(window.location.href); 
// 或者你可以直接传入一个URL字符串
const name = url.searchParams.get('name'); // "John"
const age = url.searchParams.get('age'); // "30"
console.log(name, age);

方法二:正则表达式匹配

借助正则表达式匹配 URL 参数,该方法效率相对较低且实现较为复杂,但同样能够完成参数提取任务。

function getQueryParam(name) {
  const regex = new RegExp('[?&]' + name + '=([^&#]*)', 'i')
  const results = regex.exec(window.location.href)
  return results ? decodeURIComponent(results[1]) : null
}
// 假设当前URL为 "https://example.com/?name=John&age=30"
const name = getQueryParam('name'); // "John"
const age = getQueryParam('age'); // "30"
console.log(name, age)

方法三:split 与 reduce 组合

通过 split 方法手动拆分查询字符串中的参数,再使用 reduce 将其转换为对象形式。

function getQueryParams() {    
    return window.location.search
    .substring(1) // 去掉 ?        
    .split('&') // 按 & 拆分       
    .reduce((params, param) => {            
        const [key, value] = param.split('=');            
        params[decodeURIComponent(key)] = decodeURIComponent(value || '');            
        return params;        
    }, {});
}
// 假设当前URL为 "https://example.com/?name=John&age=30"
const params = getQueryParams();
const name = params['name'];// "John"
const age = params['age']; // "30"
console.log(name, age);

方法四:基于 location.search 的自定义函数

在 location.search 的基础上构建解析函数,这种方式实现起来相对简单。

function getQueryParameter(name) {
  const params = new URLSearchParams(location.search)
  return params.get(name)
}
// 假设当前URL为 "https://example.com/?name=John&age=30"
const name = getQueryParameter('name'); // "John"
const age = getQueryParameter('age'); // "30"
console.log(name, age)

总结

本文介绍了 JavaScript 获取 URL 参数值的四种方法。如需了解更多 JS 获取 URL 参数值的相关内容,可搜索本站往期文章或继续阅读后续文章,感谢大家的支持!

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章