How to Get Query String Parameter Values From URL using JavaScript

How to Get Query String Parameter Values From URL using JavaScript

Javascript Query string URL parameters are very useful while doing CRUD operations on the server side.& from client side also we might need to get query string parameters from URL using JavaScript & modify them.

We can get query string parameters in JavaScript without using 3rd party js like jQuery etc by using

  1. Simple JavaScript code
  2. ECMAScript 6
  3. JavaScript URLSearchParams API

Javascript Query string URL parameters are very useful while doing CRUD operations on the server side.& from client side also we might need to get query string parameters from URL using JavaScript & modify them.

Get query string parameters from URL using simple JavaScript:

To get query string parameters in JavaScript,use JavaScript split() function.Further using JavaScript regular expression we can get parameters in key value pair.

Take an example of sample url https://www.arungudelli.com?param1=1&param2=--2 the query string parameter in the given url is ?param1=1&param2=2. 

var url = https://www.arungudelli.com?param1=1&param2=2;
var query_string_paramter = url.split("?")[1];   
//returns param1=1&param2=2, removing ?

Now we will use the regular expression to match pattern (“a=b”) and return paramters in json key value pair.

{param1:1,param2:2}

And if you are not passing URL parameter, it will take the current url from window.location and window.location.search will return query string parameter.

Full code snippet is  as follows

 /** 
 * This function getQueryStringParameters takes url as parmater and returns 
 * parameters name and value in JSON key value format
 * @parameter {String} url 
 * (if url is not passed it takes the current url from window.location.href) 
 *
 **/
function getQueryStringParameters(url){

 var urlParams={},
 match,
 additional = /\+/g, // Regex for replacing additional symbol with a space
 search = /([^&=]+)=?([^&]*)/g,
 decode = function (s) 
          { return decodeURIComponent(s.replace(additional, " ")); },
 query;
 if (url){
    if(url.split("?").length>0){
    query = url.split("?")[1];
 }
 }else{
    url = window.location.href;
    query = window.location.search.substring(1);
 }
 while (match = search.exec(query)){
   urlParams[decode(match[1])] = decode(match[2]);
 }
 return urlParams;
}

Get query string parameters from URL using ES6 (ECMAScript 6) :

In JavsScript,to get the query string parameters in JSON format use the following ES6(ECMAScript 6) Code snippet

/** 
* This ES6(ECMAScript) function getQueryStringParameters takes url 
* as parmater and returns
* parameters name and value in JSON key value format 
* @parameter {String} url 
* (if url is not passed it takes the current url from window.location.href) 
* 
**/
const getQueryStringParameters = url => {

    if (url){
      if(url.split("?").length>0){
      query = url.split("?")[1];
    }
    }else{
       url = window.location.href;
       query = window.location.search.substring(1);
    }
    return (/^[?#]/.test(query) ? query.slice(1) : query)
    .split('&')
    .reduce((params, param) => {
    let [ key, value ] = param.split('=');
    params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
    return params;
  }, { });
};

Get query string parameter values from URL using JavaScript URLSearchParams API:

To get query string parameter values in JavaScript, We can use UrlSearchParmas API in JavaScript.

The string parsing mechanism is ugly and old way of doing getting query string parameter values.

If you are using latest browsers like Firefox 44+, Opera 36+, Edge 17+, Safari 10.3+ and Chrome 49+ you can use UrlSearchParams API in Javascript.

Use the following code snippet to get query string parameters from current URL

 /* This URLSearchParams takes the query string as parameter */ 
var parameters = new URLSearchParams(window.location.search);

For example, if the current url is https://www.arungudelli.com?param1=1&param2=2

Now you can get parameter values by name using get(key) method of URLSearchParams API.

parameters.get('param1') //1
parameters.get('param2') //2

Or we can get parameters object by using searchParams property of URL object.

var parameters = new URL(window.location).searchParams;
parameters.get('param1') //1
parameters.get('param2') //2

If you want to get query string parameter for any url, Use the following JavaScript code snippet

var url =  new URL('https://www.arungudelli.com?param1=1&param2=2');
var parameters = new URLSearchParams(url.search);
// or by using searchParams property
var parameters = url.searchParams; 

parameters.get('param1') //1 
parameters.get('param2') //2

Apart from get(key) method UrlSearchParams also have methods like has(key) getAll(key)append(key,value), toString()

console.log(parameters.has('param1')); // true
console.log(parameters.get('param1')); // "1"
console.log(parameters.getAll('param1')); // ["1"]
console.log(parameters.toString()); // "param1=1&param2=2"
console.log(parameters.append('param3', '3')); 
// "?param1=1&param2=2&param3=3"

And we can loop through parameter keys using keys() method , values using values() method and key values using entries() method

var keys = parameters.keys();
for(key of keys) { 
console.log(key); 
}
// param1
// param2

for(val of parameters.values()){console.log(val)}
//1
//2

var entries =parameters.entries();
for(pair of entries) { console.log(pair ); } 
//["param1", "1"] 
//["param2", "2"]

Get URL parameter values by name in JavaScript:

To get URL parameter values by name in JavaScript, use the following code snippet.

 /** 
 * This function JavascriptgetURLParameterValues takes parameter name and url 
 * as parmaters and returns parameter value 
 * @parameter {String} parameterName
 * @parameter {String} url
 * (if url is not passed it takes the current url from window.location.href)
 **/

function JavascriptgetURLParameterValues(parameterName, url) {
      if (!url) url = window.location.href;
      parameterName= parameterName.replace(/[\[\]]/g, "\\><");
      var regularExpression = 
          new RegExp("[?&]" + parameterName + "(=([^&#]*)|&|#|$)"),
      results = regularExpression.exec(url);
      if (!results) return null;
      if (!results[2]) return '';
      return decodeURIComponent(results[2].replace(/\+/g, " "));
}

Now we can pass the parameter name to the above method to get URL parameter values.

var url = 'https://www.arungudelli.com?parameter1=1&parameter=2&&parameter=2';
JavascriptgetURLParameterValues("parameter1");//1
JavascriptgetURLParameterValues("parameter2");//2
JavascriptgetURLParameterValues("parameter3");//3

With the above function, you can get individual URL parameter values by passing the parameter name and URL. If you have any other snippets please do share

Thank you !

JavaScript ES6 API

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Top 10 API Security Threats Every API Team Should Know

Learn what are the most important API security threats engineering leaders should be aware of and steps you can take to prevent them

What Are Good Traits That Make Great API Product Managers

What is API product management and what can you be doing to be a better API product manager — get aligned with SaaS and enterprise software requirements. This guide lays out what is API product management and some of the things you should be doing to be a good product manager.

Consume Web API Post method in ASP NET MVC | Calling Web API | Rest API Bangla Tutorial

LIKE | COMMENT | SHARE | SUBSCRIBE In this tutorial, I will discussed about how to consume Web API Get method and display records in the ASP.NET View. Here, ...

Consume Web API Get method in ASP NET MVC | Calling Web API | Rest API Bangla Tutorial

LIKE | COMMENT | SHARE | SUBSCRIBE In this tutorial, I will discussed about How to Consume Web API Get method in ASP NET MVC. Blog : http://aspdotnetexplorer...

Consume Web API Put method in ASP NET MVC | Calling Web API | Rest API Bangla Tutorial

LIKE | COMMENT | SHARE | SUBSCRIBE In this tutorial, we learned how to consume Web API Get and Post methods in the ASP.NET View. Here, we will see how to con...