How to Get URL Parameters

URL parameters or query string parameters are used to send a piece of data from client to server via a URL. They can contain information such as search queries, link referrals, user preferences, etc..

The URLSearchParams interface makes it easier to get the parameter of the URL. It provides methods for working with the query string of a URL.

Let’s get the query string of the “https://example.com/?product=troussers&color=black&newuser&size=s” URL with window.location.search:

const queryString = window.location.search;
console.log(queryString);
// ?product=troussers&color=black&newuser&size=s

To parse the parameters of the query string, use URLSearchParams:

const urlParams = new URLSearchParams(queryString);

The URLSearchParams.get() method returns the first value that is associated with the given search parameter:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
  </head>
  <body>
    <script>
      const urlParams = new URLSearchParams("https://example.com/?product=troussers&color=black&newuser&size=s");
      const size = urlParams.get('size');
      alert(size);
      // s
      const color = urlParams.get('color')
      alert(color);
      // black      
      const newUser = urlParams.get('newuser')
      alert(newUser);
      // empty string
    </script>
  </body>
</html>

If you want to check if the given parameter exists or not, use: URLSearchParams.has():

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
  </head>
  <body>
    <script>
      const urlParams = new URLSearchParams("https://example.com/?product=troussers&color=black&newuser&size=s");
      alert(urlParams.has('size'));
      // true
      alert(urlParams.has('paymentmethod'));
      // false
    </script>
  </body>
</html>

The URLSearchParams.getAll() method returns all of the values associated with a certain parameter:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
  </head>
  <body>
    <script>
      const urlParams = new URLSearchParams("https://example.com/?product=troussers&color=black&newuser&size=s");
      alert(urlParams.getAll('color'));
      // [ 'black' ]
      //Programmatically add a second color parameter.
      urlParams.append('color', 'pink');
      alert(urlParams.getAll('color'));
      // [ 'black', 'pink' ]
    </script>
  </body>
</html>

The URLSearchParams Interface

The URLSearchParams interface specifies the utility methods to work with the query string of a URL. The URLSearchParams suggests a consistent interface to the pieces of the URL and allows a manipulation of the query string (what comes after "?").