How to Get URL Parameters in JavaScript

From WikiHTP

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:

http://www.exemple.com/recherche.php?nom=toto&age=15&ville=paris

Using window.location.search Attribute

It is possible in JavaScript to retrieve the parameters of a URL. We will use the window.location.search 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(window.location.search);
   if (results == null)
     return;
   else
     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,
        match,
        pl = /+/g, // Regex for replacing addition symbol with a space
        search = /([^&=]+)=?([^&]*)/g,
        decode = function (s) { return decodeURIComponent(s.replace(pl, )); },
        query = window.location.search.substring(1);
    urlParams = {};
    while (match = search.exec(query))
        urlParams[decode(match[1])] = decode(match[2]);
    return urlParams;
}

About This Tutorial

This page was last edited on 28 January 2019, at 07:34.