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 Lack of Rest Can Impact Your Finances Small Businesses Can Enhance File Management Following these Tips How Much Do Real Estate Agents Spend on Marketing? How to Engage Your Online Audience for Long-Lasting Success Why is Plagiarism Such a Big Deal? Resume Service Review: Why Everyone Should Use It