正则表达式获取url传参讲解
示例url:
http://localhost:8080/devicebd.html?location=30220000092&theId=2710-20200700055
function getQueryString(name) {//查找url中传递的参数信息
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]); return null;
}
其中:
-
window.location解析
location对象 含有当前URL的信息.
属性:
href 整个URL字符串.
protocol 含有URL第一部分的字符串.如:http:
host 包含有URL中主机名:端口号部分的字符.如:localhost:8080
hostname 包含URL中主机名的字符串.如:localhost
port 包含URL中可能存在的端口号字符串.如:8080
pathname URL中"/"以后的部分.如:/devicebd.html
hash "#"号(CGI参数)之后的字符串.
search "?"号(CGI参数)之后的字符串. -
正则表达式解析:
window.location.search=?location=30220000092&theId=2710-20200700055
substr(1)表示从字符串的[1]开始到结束的所有字符即’location=30220000092&theId=2710-20200700055’,
match()表示匹配的字符串, (^|&)匹配字符串开头或者&字符; (&|$)匹配&字符或者字符串结尾; -
获取r[2]是因为通过正则表达式匹配获取到的结果样式为 ["&theId=2710-20200700055&", “&”,
“2710-20200700055”, “&”, index: 30, input:
“location=30220000092&theId=2710-20200700055”, groups: undefined]
获取r[2]正好获取的是2710-20200700055