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 = || '';
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] = [];

Usage of the above method:

//Output ["123"]

//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

Get notified of the best deals on our WordPress themes.

You May Also Like
Python Write Text File

Python Write Text File

Table of Contents Hide Steps on How to write to a File in Python Python open() function Methods for Writing to a text file in PythonPython close() functionExamples for Writing to…
View Post

Scope of variables in JavaScript

What is the scope of variables in Javascript? Scope in javascript refers to the variables and the functions which are accessible and in what context it will be executed. There are…
View Post