Read query string values in JavaScript

We've all seen query strings in our browsers address bar since the beginning of the internet to the present. Despite being a Web 1.0 technology query strings are still heavily utilized in contemporary sites and web applications. Conduct a Google search and you'll see a query string appear in the results address bar.

Query strings are a handy way to pass values between pages on a site or values between different web sites without having to store the data in a cookie or on the server side using sessions or a database.

Query strings crash course

Query strings appear as follows in a browsers address bar:

https://integratedwebsolutions.tech/Resources/ReadQueryString.html?param1=value1&param2=value2

The format of a query string is as follows:

?parameter1=value1&parameter2=value2

It follows the traditional name value pair convention used in programming for decades. In the query string example above the names would be 'parameter1' and 'parameter2'. These 'name' values can be anything you like.

The values assigned to the parameters in this example are 'value1' and 'value2' via the equals sign '='.

The name value pairs 'parameter1=value1' and 'parameter2=value2' are separated by the ampersand symbol '&'

Using JavaScript we can read a query string and access the individual parameter values to use on the client side.

The JavaScript

I have a function that I wrote a few years back that I've been using to read query string values within web pages, while doing some research for this article I discovered my function has been made obsolete as the Window Web API has been updated to include functions that make reading and writing query strings very straight forward and these new functions are supported by most current browsers.

I'll discuss the function I wrote many years ago and then discuss the contemporary method that has made my function obsolete and I'll finish off the article by updating my function to use the new Window Web API methods to ready query string values.

The previous way

I wrote the function below for the purpose of reading query string values many years ago before the Window Web API added capability natively.

Line 1 contains the name of the function getQueryStringParameterValue and the parameter passed to the function is called parameterName.

There are two variables that are declared on lines 2 and 3 which are value and queryString. The variable value holds the value of the query string parameter that we are after (parameterName) and is the output of the function that is returned on line 15.

Line 3 extracts the query string value from the url in the browser address bar, the statement (window.location.href.indexOf('?') > -1)> checks for the presents of a question mark and if it is not found -1 is returned.

                        
                        
1    function getQueryStringParameterValue(parameterName) {
2        var value = '';
3        var queryString = (window.location.href.indexOf('?') > -1)? window.location.href.substring(window.location.href.indexOf('?') + 1) : "";
4        
5        if (queryString.length > 0) {
6            var nvpList = queryString.split('&');
7            for (i = 0; i < nvpList.length; i++) {
8                var nvp = nvpList[i].split("=");
9                if (nvp[0] == parameterName) {
10                  value = nvp[1];
11                  break;
12               }
13           }
14       }
15       return value;
16    }                            
                        
                    

Line 5 checks if the variable queryString contains a value by checking the length of the value it contains, if the length is greater than zero then a query string was extracted on line 3.

If we use the url https://integratedwebsolutions.tech/Resources/ReadQueryString.html?param1=value1&param2=value2 then the value assigned to queryString after line 3 exeutes is param1=value1&param2=value2.

Line 6 takes the queryString value and splits it by the & symbol this results in the nvpList variable holding two values in an array, the two values stored in the nvpList array are:

nvpList[0] contains the value param1=value1
nvpList[1] contains the value param2=value2

Line 7 begins a for loop that ends on line 13, the for loop iterates through the two values stored in the array variable nvpList.

Line 8 splits each array value (param1=value1, param2=value2) by the equals sign =.

On the first loop the array variable nvp contains the values

nvp[0] = param1
nvp[1] = value1

On the second loop the array variable nvp contains the values

nvp[0] = param2
nvp[1] = value2

nvp[0] contains the query string name and nvp[1] contains the query string value.

In line 9 we check if the variable value stored in nvp[0] equals the parameterName passed into the function.

If they are equal, we have found the query string parameter we want the value for and assign the value variable the value stored in nvp[1] which contains the query string value which the function would return.

If for instance the query string parameter we want the value for is param1 the value returned by the function would be value1 and if the parameter we were after is param2 then the function would return the value value2.

To see an example of the function in action click on the following link

The new way (hint URLSearchParams)

As alluded to earlier there is an easier way to read query string values than the way I discussed above and it's all due to the utility method URLSearchParams that was added to the JavaScript WebAPI. A word of warning the URLSearchParams function is not supported by Internet Explorer, many of you out there wouldn't be too concerned by that but Internet Explorer comes with Windows 10 and it seems Microsoft will keep Internet Explorer around until Windows 10 hits its end of extended support. Keep an eye on your sites visitor browser statistics that might tip the balance on whether your able to use the method URLSearchParams.

Using the URLSearchParams method is relatively straight forward.

                        
                            
    1        var queryString = window.location.search;
    2        var searchParams = new URLSearchParams(queryString);
    3        var parameterValue = searchParams.get('param1');
                            
                        

My sixteen line function is now replaced by two lines. Line 1 extracts the query string portion of a url that appears in the browsers address bar and stores the value in the variable queryString. Line 2 passes the queryString variable into the URLSearchParams object to create a new URLSearchParams object called searchParams.

Line 3 is where we pass the name of the query string parameter whose value we want to obtain into the get method of the searchParams object, in this cast the name of that parameter is 'param1'. If the parameter name exists in the query string then its value will be returned otherwise the null value is returned.

Using the URLSearchParams method is the fastest way to read query string parameter values from a url but you need to take into account that Internet Explorer does not support this object meaning any solution you develop with the object won't work. Ahhhh Microsoft.

Article contents: