How to get URL parameters in javascript

A URL consists of a root and some parameters that carry some data. These parameters are in the key-value pairs and separated by ‘&’ character. Also, the list of parameters and the actual URL are separated by a ‘?’ character.
This list of parameters is called URL parameters or query parameters while the complete string after the ‘?’ character is called query string.


Example,

https://www.google.com?enc=en&auth_user=u&lan=fr
Here,

actual or root URL: https://www.google.com
query parameters: enc=en, auth_user=u and lan=fr
query string: ?enc=en&auth_user=u&lan=fr

Though you can get url query string using javascript by calling window.location.search but what if you want each url(or query) parameter with its value separately.
This post will list out different methods in which you can retrieve all URL query parameters and URL parameter value with its name using javascript.
Method 1
This method works on the below steps.

  1. Create an empty object that will hold the query parameters.
  2. Retrieve the query string using window.location.search.
  3. Remove the starting ‘?’ by using substr function.
  4. Split the remaining string over ‘&’ character.
  5. Loop over the resulting array. Each array item will be a query parameter in key-value pair separated by ‘=’.
  6. Split the query parameter over ‘=’ and add first item as a key and second item as a value to the object initialized in Step 1.

Javascript code is given below.

  // initialize an empty object
  let result = {};
  // get URL query string
  let params = window.location.search;
  // remove the '?' character
  params = params.substr(1);
  // split the query parameters
  let queryParamArray = params.split('&');
  // iterate over parameter array
  queryParamArray.forEach(function(queryParam) {
    // split the query parameter over '='
    let item = queryParam.split('=');
    result[item[0]] = decodeURIComponent(item[1]);
  });
  // print result object
  console.log(result);

Above code when executed with a URL https://www.google.com?enc=en&auth_user=u&lan=fr prints the following output

{enc: “en”, auth_user: “u”, lan: “fr”}

You can use the above code as a function as given below

function getQueryParams() {
  // initialize an empty object
  let result = {};
  // get URL query string
  let params = window.location.search;
  // remove the '?' character
  params = params.substr(1);
  let queryParamArray = params.split('&');
  // iterate over parameter array
  queryParamArray.forEach(function(queryParam) {
    // split the query parameter over '='
    let item = queryParam.split("=");
    result[item[0]] = decodeURIComponent(item[1]);
  });
  // return result object
  return result;
}

Now you can easily call this function and get url parameter value by name as shown below

let parms = getQueryParams();
params('auth_user');

Note that decodeURIComponent function is only required when the value of a query parameter is a URL or has characters such as :, /, [ etc.

Method 2
This method uses regular expression to create an object of key-value pairs of query parameters.

var result = {};
window.location.search
  .replace(/[?&]+([^=&]+)=([^&]*)/gi, function(str, key, value) {
    result[key] = value;
  }
);
console.log(result);

where replace method is invoked on the query string.
It takes 2 arguments. First argument is the regular expression which matches ? and & characters in the query string.
Second argument is the callback function which is invoked every time the pattern given in the regular expression is matched in the source string.
Thus, the callback function receives a query parameter every time it is invoked and it adds the key-value pair to an object.
Method 3
Use the URLSearchParams constructor and supply the query string as an argument to it. It will return an object of key-value pairs corresponding to the URL query parameters. Example,

const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
// get the required parameter
const param = urlParams.get('lan'); // returns the value of parameter 'lan'

URLSearchParams is not supported by InternetExplorer and supported by the following browser versions

Firefox: 29 and above
Chrome: 49 and above
Edge: 17 and above
Opera: 36 and above
Safari: 10.3 and above

Hit the clap below if this post helped you in retrieving url parameters using javascript.

Leave a Reply