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]
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; }