Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Jul 2011
    Posts
    44
    Thanks
    5
    Thanked 0 Times in 0 Posts

    .match() returning blank?

    hey guys i have the following test html that i want to grab information out of in paticular .match(/\s(\d{1,2}\%)<\/td>/)[1]; now this works for the first % which returns 4%

    on this line <td style="color: white;">&nbsp;(4%)</td>

    but then i have the same matches again
    Code:
    CL = temp.match(/\s(\d{1,2}\%)<\/td>/)[1]; 
    alert("CL = " + CL); //returns 4%
    
    Neo = temp.match(/\s(\d{1,2}\%)<\/td>/)[2]; 
    alert("Neo = " + Neo);//returns undefined and should return 2%
    
    Oak = temp.match(/\s(\d{1,2}\%)<\/td>/)[3]; 
    alert("Oak = " + Oak); //returns undefined and should return 14%
    
    Queen = temp.match(/\s(\d{1,2}\%)<\/td>/)[4]; 
    alert("Queen = " + Queen); // returns undefined and should return 27%
    here is a link to the temp variable because it would get messy here
    http://pastebin.com/XFyiQ26K

  • #2
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,396
    Thanks
    12
    Thanked 569 Times in 562 Posts
    No, that's not the right way of doing it. /...(...).../ generally will only give you one match for the one group you have inside the regex. If you need to match more than once, you'll need to specify the flag /.../g for "globally" and use exec() instead of match()

    Code:
    var myReg = /\s(\d{1,2}\%)<\/td>/g;
    var match;
    while(match=myReg.exec(temp)) {
       alert(match[1]);
    }

  • #3
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,294
    Thanks
    10
    Thanked 583 Times in 564 Posts
    Code:
    
    var nums=temp.match(/&nbsp;(\d{1,2}%)<\/td>/mig).map(function(a){
     return a.split(";")[1].split("%")[0] * 1;
    });
    
    alert(nums);//shows: 4,2,14,27




    or, using .split() and non-capturing parens:
    Code:
    nums=temp.split(/[\w\W]+?(?:&nbsp;)(\d{1,2}%)(?:<\/td>)[\w\W]+?/mig).slice(1,-1).filter(String)
    alert(nums);//shows: 4%,2%,14%,27%
    Last edited by rnd me; 09-09-2011 at 07:56 PM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •