How to get query string values / URL Parameters in JavaScript

How to get query string values / URL Parameters in JavaScript, How to get query string values / URL Parameters in JavaScript, GTechHub

How to get query string values / URL Parameters in JavaScript?

URLs parameters are the easiest way to pass the variables from one web page to the other web page. In this article, I will guide you to get the URL parameter in a simple manner.

JavaScript function to get query string values

<script type="text/javascript">
 
function getQueryStringVariable(variable)
{
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for(var i=0;i<vars.length;i++) 
  {
    var pair = vars[i].split("=");
    if(pair[0] == variable){return pair[1];}
  }
  return(false);
}

</script>

Result

//Input: https://www.gtechhub.com/testpage.php?key1=value1&key2=value2&gowri=shankar

console.log(getQueryStringVariable('key1'));   // Output: value1

console.log(getQueryStringVariable('key2'));   // Output: value2

console.log(getQueryStringVariable('gowri'));   // Output: shankar

How to get query string values / URL Parameters in JavaScript, How to get query string values / URL Parameters in JavaScript, GTechHub

You Might Also Like

Leave a Reply

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