JavaScript字符串循环匹配实例分析
作者:拾光时间:2026-10-29 12:31:59浏览:630
本文介绍JavaScript中利用exec和String.match方法进行字符串循环匹配的技巧。重点说明使用exec时必须开启全局匹配g标识,才能获取所有匹配结果。通过实例展示如何提取HTML表格中的特定数据,帮助开发者掌握相关程序设计方法。
JavaScript字符串循环匹配概述
本文通过具体实例,详细解析了JavaScript中实现字符串循环匹配的技术方案,旨在为读者提供实用的参考代码与思路。
在JavaScript中,主要采用exec方法和String.match方法来进行字符串匹配操作。需要特别注意的是,若使用exec方法,必须为正则表达式开启全局匹配(g)标识,否则无法一次性获取所有匹配项。
exec与match方法的使用要点
// 需要提取这种数据 <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>(.*?)<\/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>(.*?)<\/td>/g;
// 加上g标识才会全局匹配
var matchedArray = rawData.match(regexp);
console.dir(matchedArray);
// 方法三
var regexp = /<td>(\d{4}-\d{2}-\d{2})<\/td><td>(.*?)<\/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);
希望上述关于JavaScript程序设计的说明与示例,能对读者在实际开发中处理字符串匹配问题有所帮助。
作者最新文章
JS处理含Emoji或中文的字符串转数组乱码问题
2026-11-05 16:12:28
JS怎么使用展开运算符合并对象
2026-11-05 14:42:18
ES6+环境下判断JS对象为空的简洁写法
2026-11-05 12:12:23
怎么通过replacer函数自定义JS中JSON的格式化输出
2026-11-05 11:19:44
JS正则表达式基础:字面量与RegExp构造函数的区别及常用元字符
2026-11-05 11:16:58
