Home > Web Front-end > JS Tutorial > Javascript method to obtain link (url) parameters [regular and interception of strings]

Javascript method to obtain link (url) parameters [regular and interception of strings]

高洛峰
Release: 2017-01-09 15:16:11
Original
1755 people have browsed it

当然,我们也可以用正则直接匹配,文章中也给出了一个正则的例子。 
分解链接的方式: 

<script type="text/javascript"> 
<!-- 
// 说明:Javascript 获取链接(url)参数的方法 

function getQueryString(name) 
{ 
// 如果链接没有参数,或者链接中不存在我们要获取的参数,直接返回空 
if(location.href.indexOf("?")==-1 || location.href.indexOf(name+&#39;=&#39;)==-1) 
{ 
return &#39;&#39;; 
} 

// 获取链接中参数部分 
var queryString = location.href.substring(location.href.indexOf("?")+1); 

// 分离参数对 ?key=value&key2=value2 
var parameters = queryString.split("&"); 

var pos, paraName, paraValue; 
for(var i=0; i<parameters.length; i++) 
{ 
// 获取等号位置 
pos = parameters[i].indexOf(&#39;=&#39;); 
if(pos == -1) { continue; } 

// 获取name 和 value 
paraName = parameters[i].substring(0, pos); 
paraValue = parameters[i].substring(pos + 1); 

// 如果查询的name等于当前name,就返回当前值,同时,将链接中的+号还原成空格 
if(paraName == name) 
{ 
return unescape(paraValue.replace(/\+/g, " ")); 
} 
} 
return &#39;&#39;; 
}; 

//http://localhost/test.html?aa=bb&test=cc+dd&ee=ff 
alert(getQueryString(&#39;test&#39;)); 
//--> 
</script>
Copy after login

用正则匹配的方式:

<script type="text/javascript"> 
<!-- 
function getQueryStringRegExp(name) 
{ 
var reg = new RegExp("(^|\\?|&)"+ name +"=([^&]*)(\\s|&|$)", "i"); 
if (reg.test(location.href)) return unescape(RegExp.$2.replace(/\+/g, " ")); return ""; 
}; 

//http://localhost/test.html?aa=bb&test=cc+dd&ee=ff 
alert(getQueryStringRegExp(&#39;test&#39;)); 
//--> 
</script>
Copy after login


更多Javascript 获取链接(url)参数的方法[正则与截取字符串]相关文章请关注PHP中文网!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template