Javascript: Get Query String and Key-Value Pairs from URL

In web development, it is important to know how to get query string at the client side from the URL being sent to the server. It is useful when your code (Javascript) that run at client’s browser need to know what data has been sent to the server and use the information to produce further more useful information.

To get the query string from URL is pretty simple but to get the key-value pair data is a bit more tricky. To get the full query string from URL (the URL shown on the browser’s location), you can use the following window object in Javascript:

var queryString = "";
if (window.location.search.length > 1)
    queryString = window.location.search.substring (1);

From the queryString value, you then need to split the string into key-value pairs using “&”.

var elements = queryString.split ("&");

The elements current will contain key, following by = and then follow by encoded value. For each of the splited element, we need to get it key and decode the encoded value put it into an array map.

var keyValues = {};
for(var i in elements) { 
    var key = elements[i].split("=");
    if (key.length > 1) {
      keyValues[decodeURIComponent(key[0].replace(/\+/g, " "))] = decodeURIComponent(key[1].replace(/\+/g, " "));
    }
}

And then you can use the keyValues to get the value you need in your application. For example

var value = keyValues["hello"];

Leave a Reply