JavaScript获取URL参数的三种常用方法详解
本文详解JavaScript获取URL参数的三种常用方式:利用正则表达式匹配、通过split拆分字符串以及直接调用window.location属性。文章提供了完整的代码示例与调用方法,并深入解析了location对象各属性的具体用途,帮助开发者快速掌握前端参数提取技巧。
方式一:
利用正则表达式提取URL参数(代码精简,核心在于正则匹配)
function getQueryString(name) {
let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
let r = window.location.search.substr(1).match(reg);
if (r != null) {
return unescape(r[2]);
};
return null;
}使用示例
let 参数1 = GetQueryString("参数名1"));
方式二:
基于split分割字符串(代码相对繁琐,但逻辑直观)
function GetRequest() {
const url = location.search; //获取url中"?"符后的字串
let theRequest = new Object();
if (url.indexOf("?") != -1) {
let str = url.substr(1);
strs = str.split("&");
for(let i = 0; i < strs.length; i ++) {
theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
}
}
return theRequest;
}使用示例
let Request = new Object(); Request = GetRequest(); var 参数1,参数2 ...; 参数1 = Request['参数1']; 参数2 = Request['参数2']; 参数... = Request['参数...']; 方式三:基于split分割字符串(逻辑清晰,代码规范)
function getQueryVariable(variable){
let query = window.location.search.substring(1);
let vars = query.split("&");
for (let i=0;i<vars.length;i++) {
let pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}使用示例
let 参数1 = getQueryVariable("参数名1");
补充URL相关属性知识
示例url =https://www.jb51.net/list/list_3_1.htm
1、window.location.href(用于设置或获取完整的URL字符串) console.log(window.location.href)
输出结果:http://www.jianshu.com/search?q=123&page=1&type=note
2、window.location.protocol(用于设置或获取URL的协议部分) console.log(window.location.protocol)
输出结果:http:
3、window.location.host(用于设置或获取URL的主机名部分) console.log(window.location.host)
输出结果:www.jianshu.com
4、window.location.port(用于设置或获取URL关联的端口号) console.log(window.location.port)
输出结果:空字符串(若使用默认端口80(更新:即使显式添加:80),返回值并非80而是空字符串)
5、window.location.pathname(用于设置或获取URL的路径部分,即文件地址) console.log(window.location.pathname)
输出结果:/search
6、window.location.search(用于设置或获取href属性中问号后的部分) console.log(window.location.search)
输出结果:?q=123&page=1&type=note
PS:获取查询(参数)部分,除用于动态语言赋值外,也可用于静态页面,并通过javascript获取对应参数值。
7、window.location.hash(用于设置或获取href属性中井号“#”后的片段) console.log(window.location.hash)
输出结果:空字符串(因url中未包含)
以上即为js获取url参数值的几种方式详解的详细内容,更多关于js获取url参数值的资料请关注本站其它相关文章!
let、const与var的区别:JavaScript变量声明最佳实践
2026-11-05 14:16:38
JS中直接定义静态二维数组的字面量写法
2026-11-05 14:16:08
JS 怎么查找字符串中所有匹配项的位置
2026-11-05 14:15:53
JavaScript新手常犯的编码错误与最佳实践指南
2026-11-04 22:12:38
为什么箭头函数不能直接用作JS立即执行函数
2026-11-04 21:07:26
