Extracting parameters

P

Phat G5 (G3)

I found this little script for extracting parameters from a url but wondered
what the shortest and most efficient way to do it would be, like the
following or via regexp?

function getParameter(paramName) {
var currentUrl = window.location.search
var strBegin = currentUrl.indexOf(paramName) + (paramName.length+1)
var strEnd = currentUrl.indexOf("&",strBegin)

if (strEnd==-1)
strEnd = currentUrl.length

return currentUrl.substring(strBegin,strEnd)
}


Any shorter way?


Thanks,

Steffan
 
E

Evertjan.

Phat G5 (G3) wrote on 02 jun 2007 in comp.lang.javascript:
I found this little script for extracting parameters from a url but
wondered what the shortest and most efficient way to do it would be,
like the following or via regexp?

function getParameter(paramName) {
var currentUrl = window.location.search
var strBegin = currentUrl.indexOf(paramName) +
(paramName.length+1) var strEnd = currentUrl.indexOf("&",strBegin)

if (strEnd==-1)
strEnd = currentUrl.length

return currentUrl.substring(strBegin,strEnd)
}


Any shorter way?

<script type='text/javascript'>

function getParameter(p) {
var re = new RegExp('&'+p+'=([^&]*)','i');
var c = '?apple=steve&pc=bill&a='; //window.location.search
return (c=c.replace(/^\?/,'&').match(re)) ?c=c[1] :c='NULL';
};

// Testing:
alert(getParameter('pc'));
alert(getParameter('qqq'));
alert(getParameter('aPPLE'));
alert(getParameter('A'));

</script>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top