Query Parameter using Javascript Regular Expression

Share this Article :


Friends, This post will help you out grabbing Query String parameters using Javascript. Unlike all other posts this post will do this functionality using Regular Expressions. The advantage of doing this by Regular Expression FAST.

Here the explanation of how you have to grab this parameter in traditional way
1. Take the entire query string using document.location.search
2. Split up using &
3. Now process the each string till = operator
4. check the preceding string is equal to the required parameter
5. if yes Grab it and return it

oooooopss Little Long isn’t it.

for you here is the simple code

<script>
 
function get(parameter){
var p = escape(unescape(parameter));
var regex = new RegExp("[?&]" + p + "(?:=([^&]*))?","i");
var match = regex.exec(window.location.search);
var value = null;
if( match != null ){
value = match[1];
}
if  (value.length ==0 )
return null;
else
return value;
}
</script>

Paste back the above code in to your page Head tag.

and run it as below

<script>
var q=get("q");
document.write("The Parameter Q has value of "+q);
</script>

if you are not assigning any value to Parameter is or parameter is not set then it will return you null

All the best .. Happy Coding !!

Written by admin

{admin has written 3699 posts on ITTreats.com . See all posts by }


Leave a Reply