Last Updated: October 18, 2016
·
11.58K
· kimgoulb

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?

2 Responses
Add your response

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
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