首页 > 解决方案 > 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;
}

我没有找到任何关于这种怪异的文档或线索......这是一个错误吗?还是一个陷阱,我掉进去了?有人有什么解释吗?

标签: javascriptregex

解决方案


推荐阅读