Web Analytics Made Easy -
StatCounter extracting stuff from a URL for passing variables - CodingForum

Announcement

Collapse
No announcement yet.

extracting stuff from a URL for passing variables

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • extracting stuff from a URL for passing variables

    I have a function which will extract variables from a URL such as:

    yourdomain.com/index.html?firstvar=1234&secondvar=5678

    **********************************
    <script language="JavaScript">
    function getParams() {
    var idx = document.URL.indexOf('?');
    var params = new Array();
    if (idx != -1) {
    var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
    for (var i=0; i<pairs.length; i++) {
    nameVal = pairs[i].split('=');
    params[nameVal[0]] = nameVal[1];
    }
    }
    return params;
    }
    params = getParams();
    </script>

    **********************************

    It will extract 1234 as firstvar and 5678 as secondvar when called thus:

    firstvar = unescape(params["firstvar"]);
    secondvar = unescape(params["secondvar"]);

    My question is, how do you extract the variables from a URL such as this one:

    yourdomain.com/index.html?firstvar=1234&secondvar=5678&thirdvar=91011&fourthvar=1213 etc.

    As you can see my function won't parse it correctly because there are more than one ampersands (&).

    Is there a general purpose "extraction" code out there for getting at anything within a string?

    Actually, I only need to extract three variables.

    Thanks,
    Last edited by tpeck; Oct 9, 2006, 08:16 PM.
    The difference between genius and stupidity is that genius has its limits. (Albert Einstein)

  • #2
    I think you are over complicating this. Read this thread: http://www.codingforum.net/showthread.php?t=97405
    ||||If you are getting paid to do a job, don't ask for help on it!||||

    Comment


    • #3
      I tend to overcomplicate! (Because I know so little...)

      But the methods on that page you referred me to don't seem to deal with having more than two ampersands.

      From what I read I would have to count a particular number of characters from the beginning of the string, but the URL might have a different length each time and contain different characters.

      There must be a function out there or method that can extract these four variables:

      hxxp://yourdomain.com/index.html?firstvar=1234&secondvar=5678&thirdvar=91011&fourthvar=1213

      firstvar = ???

      secondvar = ???

      thirdvar = ???

      fourthvar = ???

      ...without relying on the URL always being the same length.
      The difference between genius and stupidity is that genius has its limits. (Albert Einstein)

      Comment


      • #4
        location.search contains everything from ? onwards, so forget about finding that.
        Split works with any number of separators, so
        location.search.replace('?','').split('&');
        gives an array containing as many strings as there are url paramaters, from a quick play:
        Code:
        >>> console.log(location.search);
        ?q=firebug+extension&ie=utf-8&oe=utf-8&rls=org.mozilla:en-GB:unofficial&client=firefox-a
        
        >>> console.log(location.search.replace('?','').split('&'));
        ["q=firebug+extension","ie=utf-8","oe=utf-8","rls=org.mozilla:en-GB:unofficial","client=firefox-a"]
        My thoughts on some things: http://codemeetsmusic.com
        And my scrapbook of cool things: http://gjones.tumblr.com

        Comment


        • #5
          Thanks, I can see that the method splits the sections up into...er...further sections separated by "," which is neat.

          But I have to do hundreds of these so I was hoping for a link to a routine.

          So far I have:

          <script>
          function getParams() {
          var params = new Array();
          var idx = document.URL.indexOf('?');
          idx(location.search.replace('?','').split('&'));
          document.write("params");
          </script>

          I'm getting lost. It's probably beyond me. I'll search harder and when I find it I'll post it. I'm sure it exists and would be useful.
          The difference between genius and stupidity is that genius has its limits. (Albert Einstein)

          Comment


          • #6
            Here, I made this for you.

            Keeping with the overcomplication theme of this thread:
            Heres a script that can take urls apart for you and output them as tables.
            PHP Code:
            <html>
            <
            head>
            <
            title>URL Data extractor</title>
            <
            script type="text/javascript">
            function 
            getPairs(s){
                var 
            pairs = new Array();
                
            pairs.getValue = function(){return ''};
                var 
            str s.indexOf("?");
                if ((
            str 0)&&(str+<= s.length)){
                    var 
            pairs s.substr(str+1).split('&');
                    for (var 
            pairs.length-1>= 0i--){
                        
            pairs[i] = pairs[i].split('=');
                        for (var 
            pairs[i].length-1>= 0j--){
                            
            pairs[i][j]=unescape(pairs[i][j]);
                        }
                        while(
            pairs[i].length 2)pairs[i][pairs[i].length]='';
                    }
                    
            pairs.getValue = function(key){
                        for (var 
            i=this.length-1;i>=0;i--)
                            if(
            this[i][0] == key) return this[i][1];
                        return 
            '';
                    }
                }
                return 
            pairs;
            }

            function 
            PairHolder(p,i,o){
                var 
            pair p;
                var 
            input i;
                var 
            output o;
                
            this.fetch = function(){
                    
            o.value pair.getValue(i.value);
                }
            }

            function 
            getPairTable(s){
                var 
            getPairs(s);
                var 
            div document.createElement("div");
                
            div.appendChild(document.createTextNode("URL:"+s));
                
            div.appendChild(document.createElement("br"));
                var 
            input document.createElement("input");
                
            input.onfocus=input.select;
                
            input.setAttribute("size",15);
                
            div.appendChild(document.createTextNode("Request:"));
                
            div.appendChild(input);
                var 
            output document.createElement("input");
                
            output.onfocus=output.select;
                
            output.setAttribute("size",64);
                var 
            btn document.createElement("button");
                
            btn.appendChild(document.createTextNode("Get Value"));
                
            div.appendChild(btn);
                
            div.appendChild(output);
                
            div.appendChild(document.createElement("br"));
                var 
            ph = new PairHolder(p,input,output);
                
            btn.onclick=ph.fetch;
                var 
            document.createElement("table");
                
            div.appendChild(t);
                var 
            th document.createElement("thead");
                
            t.appendChild(th);
                var 
            document.createElement("tr");
                
            th.appendChild(r);
                var 
            document.createElement("td");
                
            d.style.textAlign="center";
                
            d.appendChild(document.createTextNode("Key"));
                
            r.appendChild(d);
                
            document.createElement("td");
                
            d.style.textAlign="center";
                
            d.appendChild(document.createTextNode("Value"));
                
            r.appendChild(d);
                
                var 
            tb document.createElement("tbody");
                
            t.appendChild(tb);
                var 
            len p.length;
                for(var 
            0leni++){
                    
            document.createElement("tr");
                    
            tb.appendChild(r);
                    for(var 
            j=0;j<2;j++){
                        
            document.createElement("td");
                        var 
            document.createElement("input");
                        
            k.setAttribute("type","text");
                        
            k.setAttribute("size",(j==0)?20:80);
                        
            k.setAttribute("value",p[i][j]);
                        
            k.onfocus k.select;
                        
            k.oValue p[i][j];
                        
            d.appendChild(k);
                        
            r.appendChild(d);
                    }
                }
                
            div.appendChild(document.createElement("hr"));
                return 
            div;
            }
            function 
            makeTables(){
                var 
            urlStrings document.getElementById("input").value.split('\n');
                var 
            output document.getElementById("output");
                for(var 
            0urlStrings.lengthi++){
                    
            output.appendChild(getPairTable(urlStrings[i]));
                }
            }
            </
            script>
            </
            head>
            <
            body>
            <
            b>Paste your URLs here.</bOnly one URL per line.
            <
            button onclick="makeTables()">Make Tables</button><br />
            <
            textarea id="input" rows="10" cols="100" style="overflow:scroll"></textarea>
            <
            br /><b>Output:</b><hr />
            <
            div id="output"></div>
            </
            body>
            </
            html
            Keeping it Simple:

            The piece of code you'll want to keep is the getPairs(string) function.
            getPairs returns an array.
            each element of the returned array is an array with two elements (key / value pair).
            the array returned also has a function attached: getValue(key) which will find a key in the array and return its value.
            PHP Code:
            var pairs getPairs("http://www.vortexcortex.com/search?user=someone&auth=234276159&terms=java%20script%20examples");

            alert("Len:"+pairs.length); // Alerts "Len:3".

            alert(pairs[0][0] +" = "pairs[0][1]); //Alerts "User = someone"

            alert(pairs.getValue("auth")); //alerts "234276159" 
            You can loop through the array returned from the getPairs function to extract each key and value.
            PHP Code:
            for (var 0pairs.lengthi++){
                var 
            key pairs[i][0];
                var 
            value pairs[i][1];
                
            //do something with the key / value pair.
                
            alertkey+"="+value );

            Last edited by VortexCortex; Oct 10, 2006, 08:26 AM. Reason: added explanation of getPairs()

            Comment


            • #7
              I am gobsmacked!

              It is quite a piece of work. Don't know what to say but thanks!

              I am sure others will be able to take advantage of it too - I certainly will.

              Every post has been of value to me. What a forum!

              Thanks once again.
              The difference between genius and stupidity is that genius has its limits. (Albert Einstein)

              Comment

              Working...
              X