在 JavaScript 中,获取 URL 参数是非常常见的操作,尤其是在 Web 开发中,常常需要获取查询字符串(query string)中的参数值来控制页面展示或进行 API 请求等操作。
方法 1: 使用 URLSearchParams 对象
 
URLSearchParams 是现代浏览器中提供的内置对象,它提供了一种方便的方法来解析和获取 URL 中的查询参数。
代码示例
假设我们有一个页面 URL 为:
https://www.example.com?user=JohnDoe&age=30&city=NewYork
我们想要获取 URL 中的参数值 user、age 和 city。
// 获取当前页面的 URL
const urlParams = new URLSearchParams(window.location.search);// 获取具体的参数值
const user = urlParams.get('user');  // 获取 'user' 参数
const age = urlParams.get('age');    // 获取 'age' 参数
const city = urlParams.get('city');  // 获取 'city' 参数console.log(`User: ${user}`);  // 输出: User: JohnDoe
console.log(`Age: ${age}`);    // 输出: Age: 30
console.log(`City: ${city}`);  // 输出: City: NewYork
解释
-  window.location.search:window.location.search会返回 URL 中的查询部分(包括?号)。比如,https://www.example.com?user=JohnDoe&age=30&city=NewYork中,window.location.search会返回"?user=JohnDoe&age=30&city=NewYork"。
-  URLSearchParams:它是一个可以轻松操作 URL 查询参数的接口。你可以使用它的get()方法来获取指定参数的值。
-  get()方法:它从查询字符串中获取特定的参数值。如果该参数不存在,它会返回null。
方法 2: 手动解析查询字符串
如果需要兼容旧版本的浏览器,或者出于某些其他需求,你可以通过原生 JavaScript 手动解析查询字符串。
代码示例
function getQueryParam(name) {const urlParams = window.location.search.substring(1);  // 获取查询字符串(去掉问号)const params = new URLSearchParams(urlParams);return params.get(name);
}// 测试
const user = getQueryParam('user');
const age = getQueryParam('age');
const city = getQueryParam('city');console.log(`User: ${user}`);  // 输出: User: JohnDoe
console.log(`Age: ${age}`);    // 输出: Age: 30
console.log(`City: ${city}`);  // 输出: City: NewYork
方法 3: 使用正则表达式解析查询字符串
有时,你可能希望使用正则表达式来解析 URL 查询参数,特别是当你需要做复杂的参数解析时。这种方法也适用于较老的浏览器。
代码示例
function getQueryParam(name) {const regex = new RegExp('[?&]' + name + '=([^&]*)', 'i');const result = regex.exec(window.location.search);return result ? decodeURIComponent(result[1]) : null;
}// 测试
const user = getQueryParam('user');
const age = getQueryParam('age');
const city = getQueryParam('city');console.log(`User: ${user}`);  // 输出: User: JohnDoe
console.log(`Age: ${age}`);    // 输出: Age: 30
console.log(`City: ${city}`);  // 输出: City: NewYork
解释
-  window.location.search:它返回 URL 中的查询部分(包括?)。在我们这个例子中,它返回"?user=JohnDoe&age=30&city=NewYork"。
-  RegExp:正则表达式的模式[?&]${name}=([^&]*)用来匹配查询字符串中指定参数的值。- [?&]表示参数名之前可以是- ?或- &。
- ${name}是你需要查找的参数名。
- ([^&]*)匹配参数值(直到下一个- &符号或者字符串结束)。
 
-  decodeURIComponent:由于 URL 编码可能会影响参数值的可读性(比如空格变成%20),所以在获取到参数后,我们使用decodeURIComponent()来解码。
方法 4: 通过 window.location 解析完整的 URL
 
如果需要解析的是整个 URL(不仅仅是查询部分),你可以使用 window.location 对象提供的不同属性(如 href, search 等)来提取信息。
代码示例
function getQueryParamFromFullUrl(url, param) {const urlObj = new URL(url);return urlObj.searchParams.get(param);
}// 示例
const fullUrl = "https://www.example.com?user=JohnDoe&age=30&city=NewYork";
const user = getQueryParamFromFullUrl(fullUrl, "user");
const age = getQueryParamFromFullUrl(fullUrl, "age");
const city = getQueryParamFromFullUrl(fullUrl, "city");console.log(`User: ${user}`);  // 输出: User: JohnDoe
console.log(`Age: ${age}`);    // 输出: Age: 30
console.log(`City: ${city}`);  // 输出: City: NewYork
解释
-  new URL(url):使用URL构造函数,可以创建一个新的 URL 对象,能够方便地访问各个部分(协议、域名、路径、查询参数等)。
-  searchParams.get():searchParams属性提供了一种访问 URL 查询参数的方式。
实际项目中的应用
在实际的项目中,获取 URL 参数常用于以下场景:
-  表单提交后的页面重定向:你可能需要在 URL 中传递状态信息,例如表单提交成功后跳转并传递用户 ID 或操作状态。 
-  分页:比如请求列表数据时,可能需要传递 page和limit等分页参数。
-  过滤器/搜索:用户在页面上进行筛选或搜索操作时,将筛选条件传递到 URL 参数中,以便能够重新加载相同的过滤状态。 
代码示例:分页功能
// 假设我们有一个分页功能,URL 如:/products?page=2&limit=20function getPaginationParams() {const urlParams = new URLSearchParams(window.location.search);const page = urlParams.get('page') || 1;  // 默认值为 1const limit = urlParams.get('limit') || 10;  // 默认值为 10return { page, limit };
}const { page, limit } = getPaginationParams();
console.log(`当前页: ${page}, 每页显示: ${limit}`);
总结
获取 URL 参数的常见方法有:
- 使用 URLSearchParams(推荐,适用于现代浏览器)。
- 使用正则表达式或手动解析(适用于老版本浏览器)。
- 使用 window.location解析完整 URL。
这些方法可以根据需求灵活选择。在现代 Web 开发中,URLSearchParams 是最简洁、易用的方式。