Home >Web Front-end >JS Tutorial >JavaScript string loop matching example analysis_javascript skills

JavaScript string loop matching example analysis_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:49:521442browse

The example in this article describes the method of javascript string loop matching. Share it with everyone for your reference. The details are as follows:

Use the exec and String.match methods. For exec, the global matching g flag must be enabled to obtain all matches

// 需要提取这种数据 <td>2012-12-17</td><td>11:02 , 12:25 , 13:22 , 15:06 , 15:12 , 19:22 , 23:47</td>
var rawData = '<table><th align="left" scope="col">日期</th><th align="left" scope="col">签到签退时间</th></tr><tr class="GridViewRowStyle" style="height:20px;">'
    + '<td>2012-12-03</td><td>10:16 , 13:22 , 20:05</td></tr><tr class="GridViewRowStyle" style="height:20px;">'
    + '<td>2012-12-04</td><td>11:16 , 14:22 , 21:05</td></tr><table>';
// 方法一
var regexp = /<td>(\d{4}-\d{2}-\d{2})<\/td><td>(.*&#63;)<\/td>/g;
// 加上g标识才会全局匹配,否则只匹配一个
var matchedArray = regexp.exec(rawData);
while(matchedArray != null) {
 console.dir(matchedArray);
 matchedArray = regexp.exec(rawData);
}
// 方法二
var regexp = /<td>(\d{4}-\d{2}-\d{2})<\/td><td>(.*&#63;)<\/td>/g;
// 加上g标识才会全局匹配
var matchedArray = rawData.match(regexp);
console.dir(matchedArray);
// 方法三
var regexp = /<td>(\d{4}-\d{2}-\d{2})<\/td><td>(.*&#63;)<\/td>/;
// 不加g标识
var matchedArray = rawData.match(regexp);
console.dir(matchedArray);
console.log(matchedArray.index);
while(matchedArray != null) {
 rawData = rawData.substr(matchedArray.index + matchedArray[0].length);
 matchedArray = rawData.match(regexp);
}
console.dir(matchedArray);

I hope this article will be helpful to everyone’s JavaScript programming design.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn