Convert a query string to an associative array in js
A simple function to convert query strings to an associative array using javascript.
var queryConvert = function(){
var queryStr = window.location.search,
queryArr = queryStr.replace('?','').split('&'),
queryParams = [];
for (var q = 0, qArrLength = queryArr.length; q < qArrLength; q++) {
var qArr = queryArr[q].split('=');
queryParams[qArr[0]] = qArr[1];
}
return queryParams;
},
This query string - ?location=us&state=georgia - should return - [ location: us, state: georgia ]
What do you think? Any better methods?
Written by Kim Goulbourne
Related protips
2 Responses
I use a very similar solution to send get links via post. In this case, i need to make a qArr[1].replace('+','%2b'), if dont, jQuery gonna crazy when make a ajax post.
over 1 year ago
·
This does not work with arrays e.g. ?names[]=Jane&names[]=John
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Query
Authors
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#