在 JavaScript 中获取 URL 参数有多种方法,适用于不同的场景,下面我将为你详细介绍几种最常用和最现代的方法。

获取当前页面 URL 的查询参数 (Query String)
这是最常见的需求,URL 是 https://example.com/?name=John&age=30,你需要获取 name 和 age 的值。
使用现代的 URL 和 URLSearchParams API (推荐)
这是目前最标准、最简洁的方法,适用于所有现代浏览器(IE 不支持)。
步骤:
- 创建一个
URL对象,传入当前页面的window.location.href。 - 使用
URL对象的searchParams属性,它是一个URLSearchParams对象。 - 通过
get()方法获取指定参数的值。
示例代码:

假设 URL 是 https://example.com/?name=John&age=30&city=Beijing
// 1. 创建 URL 对象
const url = new URL(window.location.href);
// 2. 获取 URLSearchParams 对象
const params = url.searchParams;
// 3. 使用 get() 方法获取参数值
const name = params.get('name'); // 返回 "John"
const age = params.get('age'); // 返回 "30"
const city = params.get('city'); // 返回 "Beijing"
const hobby = params.get('hobby'); // 如果参数不存在,返回 null
// 如果参数有多个值,get() 只返回第一个
// ?id=1&id=2,params.get('id') 返回 "1"
// 使用 getAll() 获取所有值
// const allIds = params.getAll('id'); // 返回 ["1", "2"]
console.log(name); // John
console.log(age); // 30
console.log(city); // Beijing
console.log(hobby); // null
优点:
- 代码简洁、易读。
- 内置处理了 URL 编码/解码(
?name=John%20Doe会被正确解码为John Doe)。 - 功能强大,可以轻松处理多值参数。
使用正则表达式 (兼容性好)
如果你需要兼容非常老的浏览器(如 IE),或者不想使用 URL API,正则表达式是一个可靠的选择。
示例代码:
function getQueryParam(param) {
// 正则表达式匹配 [?&]param=([^&]*)
// [?&] 匹配 ? 或 &
// param= 匹配参数名和 =
// ([^&]*) 匹配除了 & 之外的任意字符,并捕获到第一个分组中
const regex = new RegExp('[?&]' + param + '=([^&]*)');
const results = regex.exec(window.location.search);
// results[1] 是捕获到的值,如果没有匹配到则返回 null
return results ? decodeURIComponent(results[1]) : null;
}
// 使用示例
const name = getQueryParam('name'); // 返回 "John"
const age = getQueryParam('age'); // 返回 "30"
const hobby = getQueryParam('hobby'); // 返回 null
console.log(name); // John
console.log(age); // 30
优点:
- 兼容性极好,所有浏览器都支持。
- 不依赖任何外部库。
缺点:
- 代码可读性稍差。
- 需要手动处理 URL 解码(
decodeURIComponent)。
使用第三方库 (如 query-string)
在大型项目中,特别是使用 React/Vue 等框架时,使用专门的库来处理 URL 参数是更稳妥的选择。query-string 是一个非常流行且功能强大的库。
安装:
npm install query-string # 或 yarn add query-string
使用:
import queryString from 'query-string';
// 假设 URL 是 https://example.com/?name=John&age=30&city=Beijing
// 解析当前 URL 的查询字符串
const parsed = queryString.parse(window.location.search);
console.log(parsed);
// 输出: { name: "John", age: "30", city: "Beijing" }
// 直接访问参数
const name = parsed.name; // "John"
const age = parsed.age; // "30"
// 还可以轻松构建查询字符串
const newQuery = queryString.stringify({ name: 'Jane', age: 25 });
console.log(newQuery); // "name=Jane&age=25"
优点:
- 功能非常全面,支持解析、构建、操作查询字符串。
- 代码健壮,处理了各种边界情况。
- 在复杂项目中可以减少重复代码。
缺点:
- 增加了项目的依赖。
获取 URL 路径中的参数 (Path Parameters)
在 RESTful API 中,URL 可能是 https://api.example.com/users/123/posts/456,这里的 123 和 456 就是路径参数。
这种参数通常由后端路由框架(如 Express.js, Koa)处理,前端在 SPA(单页应用)中通过路由库(如 React Router, Vue Router)来获取。
以 React Router 为例:
假设路由配置是 path="/users/:userId/posts/:postId"。
import { useParams } from 'react-router-dom';
function UserPost() {
// useParams() 会返回一个包含所有路径参数的对象
const { userId, postId } = useParams();
console.log(`用户ID: ${userId}`); // 用户ID: 123
console.log(`帖子ID: ${postId}`); // 帖子ID: 456
// ... 组件逻辑
return <div>正在查看用户 {userId} 的帖子 {postId}</div>;
}
Vue Router 的原理类似,使用 this.$route.params 来获取。
获取哈希 (#) 后面的参数
URL 是 https://example.com/#/profile?tab=settings,这里的 tab=settings 是哈希路由的查询参数。
方法:
哈希符号 后面的部分被称为 "hash",它不属于 window.location.search,你需要先获取 hash,然后再从中解析参数。
// 假设 URL 是 https://example.com/#/profile?tab=settings&sort=asc
// 1. 获取 hash 部分,并去掉开头的 #
const hash = window.location.hash.substring(1); // 结果: "/profile?tab=settings&sort=asc"
// 2. 找到查询字符串的开始部分
const queryStringIndex = hash.indexOf('?');
if (queryStringIndex !== -1) {
// 3. 提取查询字符串
const queryString = hash.substring(queryStringIndex + 1); // 结果: "tab=settings&sort=asc"
// 4. 使用 URLSearchParams 解析
const params = new URLSearchParams(queryString);
const tab = params.get('tab'); // "settings"
const sort = params.get('sort'); // "asc"
console.log(tab, sort); // settings asc
} else {
console.log('Hash 中没有查询参数');
}
总结与推荐
| 场景 | 推荐方法 | 备注 |
|---|---|---|
获取查询参数 (?key=value) |
URL 和 URLSearchParams API |
首选方案,现代、简洁、功能强大。 |
| 正则表达式 | 用于需要兼容旧浏览器(如 IE)的环境。 | |
query-string 库 |
适用于大型项目或框架(React/Vue),功能全面。 | |
获取路径参数 (/users/:id) |
路由库 API | 如 React Router 的 useParams,Vue Router 的 this.$route.params。 |
| 获取哈希中的参数 | 手动提取 + URLSearchParams |
先处理 window.location.hash,再使用标准 API 解析。 |
对于日常开发,强烈推荐使用 URL 和 URLSearchParams,因为它已经成为 Web 标准,代码清晰且不易出错。
