JavaScript Function to get Query String

querystring in javascript

In Get Query String Value | Part 1 we described how to get query string value using core Object of JavaScript location.

Using location object to retrieve query string value is very tricky and tedious task. Therefore I came up with the simplest solution to get query string value directly.

function getQuerystringNameValue(name) {
  name = name.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");
  var regexS = "[\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return null;
    return decodeURIComponent(results[1].replace(/\+/g, " "));

In above Method we need to pass the query string name of which value you want and you will get the value of that name.

For Exampe:
You have below URL and you want the value of j.

To get the value of j you have to add above describe method in your code and call that method like given below

getQuerystringNameValue("j")  // result = 1

It also override the limitation of previous article which says

Query string must be unique or should not the part of query value

Comments Your Suggestions