Skip to content

How to Get Query String Values using JavaScript

Advertisement

We can easily get values passed in url query string using JavaScript or jQuery. Here is an simple examples of getting query string values with JavaScript. To do this create a function like getParamValuesByName and add one of example codes given below.

In the below examples function getParamValuesByName() will parse the query string values and returned matching values based on there named passed as parameter.

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>

Rahul

I, Rahul Kumar am the founder and chief editor of TecAdmin.net. I am a Red Hat Certified Engineer (RHCE) and working as an IT professional since 2009..

1 Comment

Leave a Reply

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


Back to top