Home  >  Article  >  Web Front-end  >  Summary of methods to obtain QueryString using js_javascript skills

Summary of methods to obtain QueryString using js_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:33:411415browse

本文原理是使用正则表达式匹配location.search中的字符串。其中三个主要函数为 getQueryString()、getQueryStringByName(name)和getQueryStringByIndex(index)

三个主要方法:

方法

说明

getQueryString

获取QueryString的数组。

例如路径QueryStringDemo.html?id=5&type=1&flag=0

调用后返回["id=5", "type=1", "flag=0"]

getQueryStringByName

根据QueryString参数名称获取值

getQueryStringByIndex

根据QueryString参数索引获取值

Copy code The code is as follows:

//Get the array of QueryString
function getQueryString(){
var result = location.search.match(new RegExp("[?&][^?&] =[^?&] ","g"));
for(var i = 0; i < ; result.length; i ){
result[i] = result[i].substring(1);
}
return result;
}
//Get based on QueryString parameter name value
function getQueryStringByName(name){
var result = location.search.match(new RegExp("[?&]" name "=([^&] )","i"));
if(result == null || result.length < 1){
return "";
}
return result[1];
}
//According to QueryString parameter index Get value
function getQueryStringByIndex(index){
if(index == null){
return "";
}
var queryStringList = getQueryString();
if (index > ;= queryStringList.length){
return "";
}
var result = queryStringList[index];
var startIndex = result.indexOf("=") 1;
result = result.substring(startIndex);
return result;
}

Test page path: QueryStringDemo.html?id=5&type=1&flag=0
When the page loads:

Enter the name of the QueryString to be obtained in the text box after QueryString's name to obtain the corresponding value:

Enter the name of the QueryString to be obtained in the text box after QueryString's index Index to obtain the corresponding value (the index starts from 0):

In this way, you can easily obtain the value of QueryString in the page. Finally, the source code of the test page QueryStringDemo.html is attached:
Copy the code The code is as follows:





QueryString to get the demo code www.jb51.net




QueryString :


QueryString's name :
< input id="txtQueryStringName" name="txtQueryStringName" type="text" />



QueryString's index :




Result:






pdf version download address
Statement:
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