Minifycode 2020-02-06 Viewed 1.4K times Javascript

In this article, you will learn how can I get query string values in 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.

 

var name = '@Request.QueryString["name"]';

 

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]);
   }
}

How can I get query string values in JavaScript?
minify code