Get Query String variables in JavaScript

Get Query String variables in JavaScript

the following javascript code will get the query string and return the value of the variable that was passed to this function.
<script>
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split(”&”);
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split(”=”);
if (pair[0] == variable) {
return pair[1];
}
}
alert(’Query Variable ‘ + variable + ‘ not found’);
}
</script>

Now make a request to page.html?x=Hello

<script>
alert( getQueryVariable(”x”) );
</script>

window.location.search.substring(1); will return the entire query string

split(’character ‘) will split the string at the place of occurance of the character.

Leave a Reply

You must be logged in to post a comment.


All material @ copyrighted by chrisranjana.com. If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.