2022-11-24 10:56:53
在 JavaScript 中,获取地址栏参数(即 URL 中的查询字符串参数)有多种方法,以下是三种常用且高效的方式:
1. 使用 URLSearchParams(推荐)特点:现代浏览器原生支持,语法简洁,直接通过参数名获取值。步骤:
示例代码:
// 获取查询字符串(如 "?id=123&name=test")const queryString = window.location.search;// 创建野誉 URLSearchParams 对象const params = new URLSearchParams(queryString);// 获取参数值const id = params.get('id'); // "123"const name = params.get('name'); // "test"// 检查参数是否存在if (params.has('id')) { console.log('ID 参数存在');}优点:
特点:适合简单场景或需要灵活匹配的情况。步骤:
示例代码:
const queryString = window.location.search;const regex = /[?&]id=([^&]+)/; // 匹配 ?id= 或 &id=const match = queryString.match(regex);if (match) { const id = match[1]; // "123" console.log('ID:', id);}优点:
特点:兼容性最好,但代码稍复杂。步骤:
示例代码:
const queryString = window.location.search.substring(1); // 去掉 "?"const params = {};queryString.split('&').forEach(pair => { const [key, value] = pair.split('='); if (key) params[key] = decodeURIComponent(value || '');});// 使用参数console.log(params.id); // "123"console.log(params.name); // "test"优点:
注意:以上方法均仅处理 ? 后的查询字符串,若需解析 URL 的其他部分(如哈希 #),需结合 window.location.hash 单独处理。