Home >Web Front-end >JS Tutorial >A JavaScript function parses URL parameters into Json objects_javascript skills

A JavaScript function parses URL parameters into Json objects_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:35:361359browse

Question: Please write a JavaScript function parseQueryString, which is used to parse URL parameters into an object.
eg: var obj=parseQueryString(url);

Three forms of creating objects:
1:

var Person=new Object();
Person.name="Sun";
Person.age=24;

Two:

var Person=new Object();
Person["name"]="Sun";
Person["age"]=24;

Three:
Object literal expression

var Person={
name: "Sun",
age: 24
}

PS:
1. In this example, it is more suitable to use the second form, adding elements
to obj 2. split("&"), if the url has only one parameter and there is no "&", no error will be reported, and only array[0]

will be returned.
function parseQueryString(url)
{
var obj={};
var keyvalue=[];
var key="",value=""; 
var paraString=url.substring(url.indexOf("?")+1,url.length).split("&");
for(var i in paraString)
{
keyvalue=paraString[i].split("=");
key=keyvalue[0];
value=keyvalue[1];
obj[key]=value; 
} 
return obj;
}

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