javascript - regex.test() 如何对 string.matchAll() 产生影响?
问题描述
下面代码的目标是获取字符串的所有部分,并对其之间的文本进行特殊处理* ... *
(即:加粗)。
const regex = new RegExp("([^\\*]*)*\\*([^\\*]+)\\*", "g");
const string = '*A B C*D E F*G H I*J K L*M N O*P Q R*S T U*';
const matches = string.matchAll(regex);
result = 'Result => ';
for (const match of matches) {
result += (match[1] ? match[1] : '') + (match[2] ? '<b>'+match[2]+'</b>' : '');
}
document.getElementsByTagName('body')[0].innerHTML = result;
实际上,这很好用。regex.test(string)
但是,如果我在执行所有过程之前对正则表达式 () 进行了简单的测试,则matchAll
返回的结果是不一样的(跳过字符串的开头):
const regex = new RegExp("([^\\*]*)*\\*([^\\*]+)\\*", "g");
const string = '*A B C*D E F*G H I*J K L*M N O*P Q R*S T U*';
if (regex.test(string)) {
const matches = string.matchAll(regex);
result = 'Result => ';
for (const match of matches) {
result += (match[1] ? match[1] : '') + (match[2] ? '<b>'+match[2]+'</b>' : '');
}
document.getElementsByTagName('body')[0].innerHTML = result;
}
我没有找到任何关于这种怪异的文档或线索......这是一个错误吗?还是一个陷阱,我掉进去了?有人有什么解释吗?
解决方案
推荐阅读
- firebase - 如何从 FCM 主题获取客户端 FCM 令牌
- javascript - 使用 Woocommerce 中的 jQuery 计算价格更新购物车价格
- swagger - 使用 Swagger 加载 API 定义 500 内部服务器错误失败
- c++ - 运算符一元重载函数
- batch-file - 批处理文件:如何在不关闭命令提示符的情况下执行 cmd 命令?
- android - 在 Android 中使用画布和路径创建自定义视图
- r - 如何从 R 的表格中计算百分比
- c# - 如何通过 cmake w/o 资源文件为 C# Windows Forms 应用程序设置图标?
- javascript - 如何在 jquery 对话框表中正确显示从 php 接收到的数据
- java - 请解释一下这行代码 a[s1.charAt(i) - 'a']++;