简体   繁体   中英

Return a number of matches

I am trying to get a number of matches since it matches two. Right now I am just getting one from console.log().

<script type="text/javascript">

var page = 
'<tr class="Row">' +
    '<td class="1"><p>12/31/2010</p></td>'+
    '<td class="2">'+
                '<p>text</p>'+
    '</td>'+
'</tr>'+
'<tr class="Row">' +
    '<td class="1"><p>12/01/2009</p></td>'+
    '<td class="2">'+
                '<p>text</p>'+
    '</td>'+
'</tr>'
;

var pattern = /<td class="1"><p>((\d){2}(?=\/)\/(\d){2}(?=\/)\/20(\d){2})<\/p><\/td>/;
var match = page.match(pattern);  
console.log(page);
console.log(match);

</script>

Is there a way to retrieve all the matches.

只需使用选项。

pattern = /.../gm;

I tend to use .exec() for Regex in JavaScript with the g modifier at the end of the pattern. You can then iterate over the matches by calling this multiple times until match is null:

var pattern = /<td class="1"><p>((\d){2}(?=\/)\/(\d){2}(?=\/)\/20(\d){2})<\/p><\/td>/g;
var match = pattern.exec(page);  
console.log(page);

while(match){
   console.log(match);
   match = pattern.exec(page);
}

See this working: http://jsfiddle.net/jonathon/EtpQp/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM