Open main menu

How to Get URL Parameters in JavaScript

The URL parameters are variables that will be used to transmit to the website information that will be used in the processing of the page. The parameter list starts in a URL with the? Character. The variables then follow the form variable = value and are separated by the character &.

Url example with parameters:

Using Attribute[edit]

It is possible in JavaScript to retrieve the parameters of a URL. We will use the attribute which returns the string containing the parameters of the URL. Once this string is retrieved, it will be necessary to obtain the value of the attribute according to its name. We know that the name is preceded by the character? or &, that it is followed by the sign =, and that one then finds the value, followed by either the sign &, announcing another variable, or the end of the string.

Once the value is recovered, we replace the + character with a space (because the spaces are transformed into + signs in a URL) and we apply the method decodeURIComponent() on the string. This method replaces special characters encoded in a URL with their original form. This is particularly the case for accented characters.

function getParameterByName (name)
   name = name.replace(/[[]/, [).replace(/[]]/, ]);
   var regexS = [?&] + name + =([^&#]*);
   var regex = new RegExp(regexS);
   var results = regex.exec(;
   if (results == null)
     return decodeURIComponent(results[1].replace(/+/g, ));

If you want to use a function that directly transforms the parameters of the URL into an associative array, then you will need to loop through the search() method of the Regex class. This method searches for the next occurrence of a regular expression.

function getParameters ()
    var urlParams,
        pl = /+/g, // Regex for replacing addition symbol with a space
        search = /([^&=]+)=?([^&]*)/g,
        decode = function (s) { return decodeURIComponent(s.replace(pl, )); },
        query =;
    urlParams = {};
    while (match = search.exec(query))
        urlParams[decode(match[1])] = decode(match[2]);
    return urlParams;