How to Get URL Parameters in JavaScript

In this tutorial, we are going to learn about those methods that can be used to get the URL parameters or query string values in javascript. But first, let’s have a look at the following introduction to URL parameters.

URL Parameters

These are the parameters that show an extra piece of information in the URL, these parameters or query strings contain some sort of values that are assigned dynamically.

The query string or URL Parameters start after the question mark symbol “?” in the given URL and they are commonly used for the following purposes.

  1. To sort and filter a web page.
  2. For site searching.
  3. To apply pagination for identifying pages.
  4. To show description.
  5. For translating different languages.
  6. For tracking the traffic coming from campaigns.

To get the URL parameters we are going to use an object that is called URLSearchParams Object. Let’s understand the working mechanism of this object.

URLSearchParams Object

This object is a sort of interface that provides a bunch of basic methods that can be used while working with the URL.

First of all, it will slice the strings part of the URL for getting the parameter part only.

In the URL a question mark symbol is used to dispatch both the strings and parameters parts of the URL.

The URLSearchParams object uses an entries() method that returns the key-value pairs from the URL Parameters.

These key pairs can be fetched again by accessing their index values, and the special purpose behind the usage of the entries() method is it returned all the parameters from the URL that can be used when required.

Hope you got the concept behind the URL Parameters and the URLSearchParams object, for better understanding take a look at the example below.

Example 1

<!DOCTYPE html>
<html>

<head>
    <title>how to get url parameters with javascript</title>
</head>

<body>
    
    <p> Click the below button to get the query string values in the console.</p>

    <button onclick="getstrings()"> Get query strings </button>
    <script>

    function getstrings() {
        let urlParameter =
"https://www.example.com/login.php? a=TheUrlParam&b=700&c=hi World";
        let getparamstr = urlParameter.split('?')[1];
       
let getquerystr = new URLSearchParams(getparamstr);
        for(let pair of getquerystr.entries()) {
            console.log("Key is:" + pair[0]);
            console.log("Value is:" + pair[1]);
        }
    }
 </script>
</body>
</html>

Code Explanation

In the above code, we used the basic HTML structure.

In the body tag we created a button with an onclick function ”getstrings” that will execute when the user will click on it. 

After that we wrote a script in which we declared the getstring function, firstly we declared a variable and assigned it a dummy URL, and then we declared 2 variables “getparamstr” and “getquerystr”.

We assigned the split() function to “getparamstr” variable that will separate the parameter part after the question mark symbol from the URL, and then we passed the parameters to the “getquerystr” variable.

We used the entries() method to get the key pair values from the parameters and then in the end we consoled the values 

Check out the results below.

Output

Key is: a
index.html:21 Value is:TheUrlParam
index.html:20 Key is:b
index.html:21 Value is:700
index.html:20 Key is:c
index.html:21 Value is:hi World

As you can see above output returned each parameter with its value.

We have another way to get the parameters from the URL, basically, we can call it a technique.

The technique is that we can access and separate each string pair by using split(), and loop functions. Let’s understand this concept in a depth:

First of all, we will follow the same trick by splitting out the parameter part from the URL by using the question mark symbol “?” as a separator, then we will use another separator “&” that is called “And” this operator will help to dispatch each string parameter into an array.

That array will iterate through a loop that will dispatch the keys and values with the equal operator “=”.

Check out the following example to have a clear concept.

Example 2

<!DOCTYPE html>
<html>

<head>
    <title>how to get url parameters with javascript</title>
</head>

<body>
    
    <p> Click the below button to get the query string values in the console.</p>

    <button onclick="getstrings()"> Get query strings </button>

    <script>
    function getstrings() {
        let urlParameter =
"https://www.example.com/login.php? a=TheUrlParam&b=700&c=hi World";
        let getparam_str = urlParameter.split('?')[1];
        let getparam_arr = getparam_str.split('&');
        for(let i = 0; i < getparam_arr.length; i++) {
            let pair = getparam_arr[i].split('=');
            console.log("Key is:" + pair[0]);
            console.log("Value is:" + pair[1]);
        }
    }
    </script>
</body>

</html>

Code Explanation

You can see the above code, we used a basic structure of HTML and created a button with an onclick function in the body tag as we did in the previous example.

In the script we declared a function that will console the key values of parameters.

To create this functionality we used the split() function to separate the parameters from the URL then we used the “&” operator and length feature inside a loop, we used this trick to dispatch each parameter string in the array, and then the loop will dispatch key pairs in the form of an array.

In the end, we console the key values see the results below.

Output

Key is: a
index.html:23 Value is:TheUrlParam
index.html:22 Key is:b
index.html:23 Value is:700
index.html:22 Key is:c
index.html:23 Value is:hi World

As you can see above it also returned the same output as our previous method returned which means you can use both methods as per your need.

Conclusion

In this tutorial, we talked about the methods that can be used to get the parameter value or query strings from a URL with Javascript.

First, we saw a brief introduction to the URL Parameters then we discussed a short introduction to our first method called “the URLSearchParam Object” with an example.

We also discussed the code and saw its output, then we moved forward to the next method in which we used the “&” operator and loop and discussed them with an example.

In the end, we explained the code and saw its output as well.

That’s all for today hope you like the tutorial if you have any queries regarding this tutorial so feel free to contact us below. Thanks for reading. 

Leave a Comment