How to get query string values in JavaScript

In this tutorial, we will discuss how to get string values in JavaScript.

Today, we’ll learn several efficient solutions to get query string values in JavaScript.

1. How to get a specific query string

const getSpecificQuery = ( params, url ) => {
  let hreflink = url;
  let expreg = new RegExp( '[?&]' + params + '=([^&#]*)', 'i' );
  let stringquery = expreg.exec(hreflink);
  return stringquery ? stringquery[1] : null;
};
console.log(getSpecificQuery('data','http://example.com?example=something&data=32'));

The function getSpecificQuery takes params and url as parameters. Inside the function, we created the variable hreflink and assigned url to it.

Regex pattern stores the value after ‘=’ in queryString and returns it.

2. How to get all query strings

const getallQuery = (url) => {
  let paramsallq = {};
  let anchor = document.createElement('a');
  anchor.href = url;
  let stringsallq = anchor.search.substring(1);
  let params = stringsallq.split('&');
  for (let i = 0; i < params.length; i++) {
    let pair = params[i].split('=');
      paramsallq[pair[0]] = decodeURIComponent(pair[1]);
    }
    return paramsallq;
};
console.log(getallQuery('http://example.com?example=something&data=24'));

The function getallQuery takes url as a parameter. Inside the function, we assigned the url to href. We also created an anchor element and property search, which returns the queryString.

 3. Query String in Vanilla JavaScript

function getQueryString(key) { 
     var arrParam = []; 
     var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); 

     for (var i = 0; i < url.length; i++) { 
          var arrParamInfo = url[i].split('='); 
          
          if (arrParamInfo[0] == key || arrParamInfo[0] == key+'[]') { 
              arrParam.push(decodeURIComponent(urlparam[1])); 
           } 
     } 

     return (arrParam.length > 0 ? (arrParam.length == 1 ? arrParam[0] : arrParam) : null); 
} 

// index.php?keyword=noway&hobbies[]=cricket&hobbies[]=singing 
console.log(getQueryString('keyword')); // "noway" 
console.log(getQueryString('hobbies')); // Array [ "cricket", "singing" ] 
console.log(getQueryString('keyNotExits')); // null

We have created the function, which takes key as a parameter and get the value of query string present in the URL.

Leave a Reply

Your email address will not be published. Required fields are marked *