js获取浏览器地址栏里的参数

代码如下: 

function getvalue(name) {
    var str = window.location.search;
    if (str.indexOf(name) != -1) {
        var pos_start = str.indexOf(name) + name.length + 1;
        var pos_end = str.indexOf("&", pos_start);
        if (pos_end == -1) {
            return str.substring(pos_start);
        }
    }
}
var typeValue = getvalue("type");//调用函数,获取地址栏里的参数  type为地址栏里的参数名
//typeValue是地址栏里type的值

 

在前端开发中,获取浏览器地址栏(URL)中的参数是一个常见的需求。通常这些参数位于 URL 的查询字符串(query string)部分,形式为 `?key1=value1&key2=value2`。 以下是几种获取浏览器地址栏参数的方法,使用 JavaScript 实现: ### 方法一:使用 URLSearchParams API(推荐,现代浏览器) ```javascript // 获取当前 URL 的查询参数 function getUrlParams() { const params = new URLSearchParams(window.location.search); const result = {}; for (let [key, value] of params) { result[key] = value; } return result; } // 使用示例 const queryParams = getUrlParams(); console.log(queryParams); // 例如: {name: "john", age: "30"} ``` **解释:** - `window.location.search` 返回 URL 中 `?` 及其后面的部分,例如 `?name=john&age=30`。 - `URLSearchParams` 是一个内置接口,用于处理查询字符串,支持 `.get(key)`、`.getAll(key)`、`.has(key)` 等方法。 - 遍历 `params` 可以将所有键值对提取到一个对象中。 > ✅ 优点:简洁、标准、可读性强,支持数组参数(如 `tags=js&tags=css`) > ❌ 缺点:不兼容 IE 浏览器 --- ### 方法二:手动解析(兼容性好,适用于老浏览器) ```javascript function getUrlParamsManual() { const query = window.location.search.substring(1); // 去掉 '?' const params = {}; if (!query) return params; const pairs = query.split('&'); for (let pair of pairs) { const [key, value] = pair.split('='); params[decodeURIComponent(key || '')] = decodeURIComponent(value || ''); } return params; } // 使用示例 const queryParams = getUrlParamsManual(); console.log(queryParams); ``` **解释:** - `substring(1)` 去除开头的 `?` - `split('&')` 拆分每个参数对 - `split('=')` 分离 key 和 value - 使用 `decodeURIComponent` 解码中文或特殊字符(如 `%E4%B8%AD` → “中”) > ✅ 优点:兼容性好,可在 IE 中运行 > ❌ 缺点:代码较多,需手动处理编码和边界情况 --- ### 方法三:使用正则表达式提取特定参数 ```javascript function getQueryParam(key) { const regex = new RegExp(`[?&]${encodeURIComponent(key)}(?=\\=|$)`); const match = window.location.search.match(new RegExp(`[?&]${key}=([^&]*)`)); return match ? decodeURIComponent(match[1]) : null; } // 使用示例 const name = getQueryParam('name'); console.log(name); // 输出 name 参数的值 ``` **解释:** - 正则匹配指定参数名后的值 - `encodeURIComponent(key)` 处理特殊字符 - 如果参数不存在返回 `null` > ✅ 优点:适合只取单个参数 > ❌ 缺点:多次调用效率低,不适合获取全部参数 --- ### 方法四:封装成可复用工具类(推荐用于项目) ```javascript class UrlParams { constructor(search = window.location.search) { this.params = new URLSearchParams(search); } get(key) { return this.params.get(key); } getAll(key) { return this.params.getAll(key); } has(key) { return this.params.has(key); } toString() { return this.params.toString(); } } // 使用示例 const urlParams = new UrlParams(); console.log(urlParams.get('name')); console.log(urlParams.getAll('tag')); // 多值情况 ``` --- ### 补充:Vue/React 中的使用建议 - 在 Vue 中可结合 `vue-router` 的 `this.$route.query` - 在 React 中可使用 `useSearchParams()`(React Router v6) --- ### 示例 URL: 假设当前 URL 是: ``` https://example.com/page?name=张三&age=25&hobby=reading&hobby=traveling ``` 使用 `URLSearchParams` 获取: ```js const params = new URLSearchParams(location.search); console.log(params.get('name')); // "张三" console.log(params.getAll('hobby')); // ["reading", "traveling"] ``` --- ### 注意事项: - 中文参数需 `encodeURIComponent` 发送,接收时自动解码(但手动解析时要用 `decodeURIComponent`) - 单值 vs 多值参数要区分使用 `.get()` 和 `.getAll()` - `#hash` 不影响查询参数 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值