How to Get Query String Values using JavaScript

Table of Contents

JavaScript and jQuery can be used to easily retrieve values from URL query strings. This is an example of JavaScript obtaining query string values. Create a function such as getParamValuesByName, and then add one of the example codes below.

Function is demonstrated in the following examples getParamValuesByName() It will parse query string values and return matching values based upon their names passed as parameters.

Example 1:

<script type="text/javascript">
function getParamValuesByName (querystring) {
  var qstring = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
  for (var i = 0; i < qstring.length; i++) {
    var urlparam = qstring[i].split('=');
    if (urlparam[0] == querystring) {
       return urlparam[1];
    }
  }
}
var uid = getParamValuesByName('uid');
var uname = getParamValuesByName('uname');
</script>

Example 2:

<script type="text/javascript">
function getParamValuesByName (querystring) {
    name = querystring.replace(/[[]/, "\[").replace(/[]]/, "\]");
    var regexS = "[\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.search);
    if (results == null) {
	    return "";
	}
    else {
	    return decodeURIComponent(results[1].replace(/+/g, " "));
	}
}

var uid = getParamValuesByName('uid');
var uname = getParamValuesByName('uname');
</script>

 

How To Use Data Analytics To Improve Email Marketing Campaigns Top 8 Dominating Mobile App Trends in 2022 How to make a car safe for long journeys? Everything You Expect to Learn About VPN for Windows Top 7 Benefits of B2B Marketing Strategy Characteristics Held in common with All Customer-Friendly LMS Solutions