JS获取当前浏览器URL参数(中英文通用)

一、获取浏览器参数方法

function getParams(key) {
    let search = window.location.search.replace(/^\?/, "");
    let pairs = search.split("&");
    let paramsMap = pairs.map(pair => {
        let [key, value] = pair.split("=");
        return [decodeURIComponent(key), decodeURIComponent(value)];
    }).reduce((res, [key, value]) => Object.assign(res, { [key]: value }), {});
    return paramsMap[key] || "";
}

 

说明:

1、window.location.search:是获取URL地址的查询部分 eg: " ?name=dingFY&age=18 "

2、window.location.search.replace(/^\?/, ""):去掉查询部分的 " ? "

3、search.split("&"): 将查询部分字符串以&为分界切割成数组

4、遍历数组,将数组的每一项以=为分界进行切割保存为键值对,对键和值进行URL解码,再合成为对象

5、从对象中返回用户指定key键的value值

 

二、decodeURIComponent()函数

decodeURIComponent() 函数可对 encodeURIComponent() 函数编码的 URI 进行解码。

语法: decodeURIComponent(URIstring)

参数:URIstring:必需,一个字符串,含有编码 URI 组件或其他要解码的文本。

返回值:URIstring 的副本,其中的十六进制转义序列将被它们表示的字符替换。

举例:

let tast="http://www.baidu.com/My first/"

document.write(encodeURIComponent(test)+ "<br />")
document.write(decodeURIComponent(test))


// 页面输出:
// http%3A%2F%2Fwww.baidu.com%2FMy%20first%2F
// http://www.baidu.com/My first/

三、举例

假设当前页面的URL为:

 http://localhost:8088/todayMeetingMessage.html?organizeCode=44030022&organizeName=%22%E9%BB%84%E5%9F%94%E7%9C%8B%E5%AE%88%E6%89%80%22#/dispatch

调用getParams()方法获取organizeCode的参数值

function getParams(organizeCode) {
    let search = window.location.search.replace(/^\?/, ""); 
    // organizeCode=44030022&organizeName=%22%E9%BB%84%E5%9F%94%E7%9C%8B%E5%AE%88%E6%89%80%22

    let pairs = search.split("&"); 
    // ["organizeCode=44030022", "organizeName=%22%E9%BB%84%E5%9F%94%E7%9C%8B%E5%AE%88%E6%89%80%22"]

    let paramsMap = pairs.map(pair => {
        let [key, value] = pair.split("=");
        return [decodeURIComponent(key), decodeURIComponent(value)];
    }).reduce((res, [key, value]) => Object.assign(res, { [key]: value }), {});
    // {organizeCode: "44030022", organizeName: ""黄埔看守所""}

    return paramsMap[organizeCode] || ""; 
    // 44030022
}

文章每周持续更新,可以微信搜索「 前端大集锦 」第一时间阅读,回复【视频】【书籍】领取200G视频资料和30本PDF书籍资料

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@Demi

您的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值