How to Get Query String Values using JavaScript

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>