JavaScript获取URL中参数值的四种方法
作者:闭包旅人时间:2026-10-31 20:04:22浏览:615
本文介绍了在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 参数值的相关内容,可搜索本站往期文章或继续阅读后续文章,感谢大家的支持!
作者最新文章
什么时候该用JS构造器:与工厂模式、字面量的选择对比
2026-11-05 16:18:22
推荐几款轻量级JS照片墙开源库及对比
2026-11-05 15:56:19
JavaScript递归写法有哪些常见陷阱及避免方法
2026-11-05 14:53:38
JS数组浅拷贝与深拷贝怎么选?场景与方法总结
2026-11-05 14:41:02
p5.js 中 setup() 和 draw() 函数的执行机制详解
2026-11-05 12:32:38
