Wednesday, June 3, 2009

Extracting URL parameters with Javascript

I found this very nice script over at 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
You can extract out the realm or the name value using the script
var myStr = '';
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