Home >Web Front-end >JS Tutorial >JavaScript extracts parameters in the search string of the URL (custom function implementation)_javascript skills

JavaScript extracts parameters in the search string of the URL (custom function implementation)_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:43:14988browse

Today I found a useful function urlArgs (extracts the parameters in the search string of the URL) in the Rhino book. We often see that some page link addresses are followed by parameters, such as http://www.xxx.com/?username=yyy&password=zzz. Many times we need to obtain the values ​​​​of these parameters (yyy and zzz ), then you can use the urlArgs function to obtain it through the properties of the function's return value (the return value is an object).

urlArgs function code:

Copy code The code is as follows:

function urlArgs(){
var args = {};
var query = location.search.substring(1);
var pairs = query.split('&');
for(var i = 0; i < pairs.length; i ){
var pos = pairs[i].indexOf('=');
if(pos == -1) continue;
var name = pairs[i].substring(0,pos);
var value = pairs[i].substring(pos 1);
value = decodeURIComponent(value);
args[name ] = value;
}
return args;
}

Usage :
Copy code The code is as follows:

var args = urlArgs();
var username = args.username; //yyy
var password = args.password; //zzz
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