4 Ways Get Query String Values from URL Parameters in JavaScript or jQuery

Sometimes we need to get values through the query string in the URL on the browser address bar. But the question is how to get them in JavaScript or jquery because we need them on the client-side.

Here I’m mentioning 4 ways for getting values from query parameters. I have also displayed uses examples. You can use either of them as per your choice and need in the client-side JS or jQuery.

Get Query String Values from URL Parameters

1. Retrieve Query String Values using URLSearchParams

This is the simplest and most recommended way to retrieve values from the query string. URLSearchParams is a built-in interface in the latest browsers with a number of methods to get and manipulate values.

While this interface supports a number of decent browsers, it is not available for all, especially old ones. I suggest checking the official documentation on Mozilla and Chrome. It has various useful methods to utilize.

2. Regular Expression in JavaScript

Here is the function which will safely decode URL components using a regular expression. We can call this function and pass the query string parameter’s name as an argument to obtain the value.

Suppose we have the URL as follows: http://example.com/sports?game=football.

If we wish to retrieve the value for the game query parameter, we can pass it to the qsp variable as a string and we will get football as value. If the parameter doesn’t exist then the function would simply return an empty string.

3. Simple JavaScript Function to get Query Parameters Values Object

We can also get the whole query string as an object and then access the value of a particular parameter by its key.

The function above performs the following steps:

  1. Getting the URL
  2. Parsing query string by splitting the URL
  3. Looping through each and every key in the parsed query string
  4. Storing every key and its value as an object
  5. Return the object

Below is an example:

4. jQuery Way to Get Query String Values from URL Parameters

If you want a jQuery way to get a specific URL parameter’s value then here is the function.

Hope these 4 functions will help you to get values of query string parameters in a URL. If you have any queries or any jQuery/JavaScript issue then feel free to contact us.

You Might Interested In

1 COMMENT

  1. Juan Carlos Neufeld says:

    Hi Amit!
    Very good post.
    3. Simple JavaScript Function works fine for me.
    Thank’s from Argentine.

    Reply

Leave a Reply

Enclose a code block like: <pre><code>Your Code Snippet</code></pre>.