Wednesday, June 3, 2009

Extracting URL parameters with Javascript

I found this very nice script over at Netlobo.com that will extract the desired parameter from browser URL (see the article here). Maybe I can explain this better with examples.

Here is a basic browser URL
http://www.somegame.com/character.php?realm=MyRealm&name=Motty
You can extract out the realm or the name value using the script
var myStr = 'http://www.test.com/character.php?realm=MyRealm&name=Motty';
document.write ( gup('name', myStr) );
// outputs: Motty

document.write ( gup('realm', myStr) );
// outputs: MyRealm
Here is the modified code:
function gup(n,s){
n = n.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");
var p = (new RegExp("[\\?&]"+n+"=([^&#]*)")).exec(s);
return (p===null) ? "" : p[1];
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.