JavaScript获取URL参数的三种常用方法详解

作者:青柠

时间:2026-10-30

浏览:258

本文详解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参数值的资料请关注本站其它相关文章!

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章