A JavaScript function parses the URL parameter into a Json object

  • 2020-03-30 03:59:21
  • OfStack

Problem: write a JavaScript function, parseQueryString, that parses the URL parameter into an object.
Eg: var obj = parseQueryString (url);

There are three ways to create an object:
A:


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

2:


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

Three:
Object literal expression


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

PS:
1. In this case, it is better 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;
}


Related articles: