JavaScript: How to Get Query String Parameter Value from Current Page URL

You can retrieve any query string value based on parameter name from the url of current page. Following JavaScript function returns the value for given parameter name. These are raw JavaScript codes, so you don’t need to use jQuery.
Method 1 :

function getParameterByName(name)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexString = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexString);
  var found = regex.exec(window.location.search);
  if(found == null)
    return "";
  else
    return decodeURIComponent(found[1].replace(/\+/g, " "));
}

Your url parameters may be url-encoded and you want to get decoded value, this function return decoded value. There are an alternative way to write this function. Following function do the same work like above function. You may use following codes instead.

Method 2 :


function getParameterByName(name) {
 return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}

When your given parameter name is not exists in the url then this function returns null instead of ‘null’.

Using jQuery

I found two jQuery plugins to get url parameter value

To learn more critical points to play with URL query string parameters you may go to following discussion pages.
Reference 1 , Reference 2

This function returns the answer of following queries

  • JavaScript to read a URL query string
  • Getting Query String Parameters with JavaScript
  • Javascript to get Query String from URL in raw JavaScript
  • Get URL and URL Parts in JavaScript
  • Get Current Page QueryString Using JavaScript
  • JavaScript Function to Get URL Query Values
  • Raw JavaScript and URL parameters
  • JavaScript to Read GET variables from URL

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *