JS:获取指定的url参数,或者全都要(以对象的形式)

    技术2025-09-03  27

    进入我的主页,查看更多JS的分享!

    我的代码有多短,本文章就有多短!(ㅍ_ㅍ)

    1. 思路

    获取浏览器得参数的字符串,判断并转为对象,如果没有指定参数名,直接返回该对象。

    2. 代码

    需要说的话都在注释里了,先贴上代码:(好像明白了程序员为啥话不多)

    /** * 获取:当前链接的参数 * 若不指定参数,则以对象的形式返回全部参数 * 若指定参数名,则只返回对应的值 * 处理:中文解码 * 测试:"?id=123&name=哈哈哈" * 结果:{id: "123", name: "哈哈哈"} */ var getLocationParam = (name) = >{ let param = window.location.search.substr(1); if (!param) { return undefined; } else { let pArr = param.split("&"); let res = {}; for (let i = 0; i < pArr.length; i++) { let item = pArr[i].split("="); res[item[0]] = item[1] ? decodeURI(item[1]) : null; } return !name ? res: res[name]; } };

    如果参数有中文,直接用"decodeURI()",而"unescape()"并不适用。(测试了QQBrowser、Chrome、IE9-11)

    运行:

    console.log(getLocationParam("id")); //输出:123 console.log(getLocationParam("name")); //输出:哈哈哈 console.log(getLocationParam("due")); //输出:undefined console.log(getLocationParam()); //输出:{id: "123", name: "哈哈哈"}

    下载文件()

    还有一个代码,是用正则来获取指定的参数。嘛,直接贴上代码看看吧:

    /** * 获取:当前链接的指定的参数 * 方法:采用正则 */ var getLocationQueryByName = (name) = >{ var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); var r = window.location.search.substr(1).match(reg); if (r != null) return decodeURI(r[2]); return null; };

    Processed: 0.011, SQL: 9