Extracting parameters

Discussion in 'Javascript' started by Phat G5 (G3), Jun 2, 2007.

  1. Phat G5 (G3)

    Phat G5 (G3) Guest

    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
    Phat G5 (G3), Jun 2, 2007
    #1
    1. Advertising

  2. Phat G5 (G3)

    Evertjan. Guest

    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>


    --
    Evertjan.
    The Netherlands.
    (Please change the x'es to dots in my emailaddress)
    Evertjan., Jun 2, 2007
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jonck van der Kogel
    Replies:
    2
    Views:
    976
    Jonck van der Kogel
    May 27, 2004
  2. sunil

    Extracting the query parameters

    sunil, Jan 22, 2007, in forum: ASP .Net
    Replies:
    6
    Views:
    429
    sunil
    Jan 23, 2007
  3. Jason
    Replies:
    2
    Views:
    506
    Jonathan Mcdougall
    May 13, 2006
  4. kito
    Replies:
    2
    Views:
    413
  5. Florian Loitsch
    Replies:
    11
    Views:
    245
    Michael Winter
    Mar 15, 2005
Loading...

Share This Page