ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、视频、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
``` function getUrl(type){ var url=window.location.href; var param; if (url.indexOf('?') != -1) { url=url+'&solution_type='+type; } else { url=url+'?solution_type='+type; } console.log(url) } ``` 获取当前页面指定的get请求参数 ``` //获取url中的参数 不存在返回null function getUrlParam(name) { //封装方法 var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象 var r = window.location.search.substr(1).match(reg); //匹配目标参数 if (r != null) return decodeURI(r[2]); return null; //返回参数值 } ``` ### window.location: window的location对象 1. window.location.href   整个URl字符串(在浏览器中就是完整的地址栏) 2. window.location.protocol   URL 的协议部分   返回值:http: 3. window.location.host   URL 的主机部分(带端口号) 4. window.location.port   URL 的端口部分。 5.window.location.pathname   URL 的路径部分(就是文件地址) 5. window.location.search   查询(参数)部分。得到的是url中?部分。除了给动态语言赋值以外,我们同样可以给静态页面,并使用javascript来获得相信应的参数值。 6. window.location.hash   锚点。得到的是url中#部分。 ### substr() 返回一个从指定位置开始的指定长度的子字符串 这里设置为1,是为了把url中的?号去掉 ### reg ~~~jsx function getQueryString(name) { var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); //(^|&)education_serve_type=([^&]*)(&|$) 《=》?cate=1&education_serve_type=1 var r = window.location.search.substr(1).match(reg); alert(r)//&education_serve_type=1,&,1, alert(decodeURI(r[0]))//&education_serve_type=1 alert(decodeURI(r[1]))//& alert(decodeURI(r[2]))//1 if (r != null) { return unescape(r[2]); } return null; } ~~~ 1、reg是一个正则表达式子,是你获得的参数 ![](https://img.kancloud.cn/c3/95/c3957b5e8446335772cd98f44422657b_1200x403.png) var reg = new RegExp("(^|&)"+ name +"=(\[^&\]\*)(&|$)"); (^| )代表开始 ( |$)代表结束 以&或者$结尾的字符串 这个正则是寻找&+url参数名字=值+& &可以不存在。 2. window.location.search.substr(1).match(reg); (1) location是包含了相关的url的信息,它是windown的一部分。 (2) search是一个可以查询的属性,可以查询?之后的部分。 (3) substr(1)是为了去掉第一个? (4) match()是你要匹配的部分 后面可以是正则表达式。 (5) return unescpe(r\[2\]) 返回的值 一个数组。 (6) 这里是开始匹配,找到了返回对应url值,没找到返回null。