How to get query string values using JavaScript?

Here is a very simple method to get query string values using javascript. Below code snippet can be used to fetch the query string value in the URL when the key is provided in the params variable.

Example to Get Query String values using Javascript:

var queryString = window.location.search || '';
var keyValPairs = [];
var params      = {};
queryString     = queryString.substr(1);

if (queryString.length)
{
   keyValPairs = queryString.split('&');
   for (pairNum in keyValPairs)
   {
      var key = keyValPairs[pairNum].split('=')[0];
      if (!key.length) continue;
      if (typeof params[key] === 'undefined')
         params[key] = [];
      params[key].push(keyValPairs[pairNum].split('=')[1]);
   }
}

Usage of the above method:

//url= https://itsmycode.com/how-to-get-query-string-values-in-javascript?query=123&list=default
params['query'];
//Output ["123"]

params['list'];
//Output ["default"]

//Note: If the querystring value is empty the method will return the value as empty string.
Leave a Reply

Your email address will not be published.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like
Powershell Concatenate String

PowerShell Concatenate String

Table of Contents Hide Introduction to PowerShell Concatenate StringHow to Concatenate Strings and Variables in PowerShell#1. Expanding Strings#2. Substitution or string.Format approach#3 Join Operator Microsft PowerShell scripting is little different from…
View Post