Search This Blog

Dec 7, 2011

Javascript: Get Query String Function

In order to get the query string in the URL, we need to split the URL using split method. We can simply get it by using the following code:
http://www.sample.com?test=value 
<script>
var  queryString = window.location.search.substring(1); 
alert(queryString);  //output test=value 
</script>
In the above code, we split the URL using window.location.search.substring(1); code and pass the value on the queryString variable. Then, alert it. Take note that (1) is referring to the part of url after the question mark. So in other words if we put (0) on the parameter, what we got is the "http://www.sample.com".
If you want to chunk the query string by each variable and value, this function might help you.

<script type="text/javascript">
<!--

function getQueryString(sVar) {
urlStr = window.location.search.substring(1);
sv = urlStr.split("&");
for (i=0;i< sv.length;i++) {
ft = sv [i].split("=");
if (ft[0] == sVar) {
return ft[1];
}
}
}

var splitStr = getQueryString ("fieldName");

alert(splitStr);

-->
</script>

4 comments:

Jenessa said...

these examples are self explainatory..nice efforts.will try this on any  Web Design Sheffield

Cheap Website Builders said...

Hi, Admin Cheers for the great post, we are one of the best בניית אתרים בזול in the world, providing excellent quality and reliable design. try us then you will let know our outstanding work.

WSS said...

Exactly what I was after, thanks. You've saved my skin before a tight deadline.

Anonymous said...

really help full for me

thanks