string.matchAll(regex) 在浏览器中表现奇怪

问题描述 投票:0回答:1

我使用正则表达式来匹配node.js 中的markdown。但我试图在react.js 应用程序中运行它,但收效甚微......

  const regex = /(\*\*\*|___|\*\*|\*|__|\[.*?\]\([^)]*\))(.*?)(\1|$)/g;

  const matches = markdown.matchAll(regex);

  for (const match of matches) {
    console.log(match);
  }

当我使用示例输入在 node.js 中运行代码时:

'normal text **bold** *italic* normal'

我得到输出:

[
  '**bold**',
  '**',
  'bold',
  '**',
  index: 12,
  input: 'normal text **bold** *italic* normal',
  groups: undefined
]
[
  '*italic*',
  '*',
  'italic',
  '*',
  index: 21,
  input: 'normal text **bold** *italic* normal',
  groups: undefined
]

但是当我在我的 React 应用程序中运行相同的代码时,在 Edge (120.0.2210.133) 和 chrom (120.0.6099.225) 中

matches
记录为:

RegExpStringIterator {}

当我尝试迭代它并记录每个项目时

for (const match of matches) {
    console.log(match);
}

与 Node.js 不同,我什么也没得到

但是根据:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll我应该得到与在node.js中类似的输出,并且根据https://caniuse.com/mdn-javascript_builtins_string_matchall chrome 和 endge 都应该完全支持

matchAll

为了进行完整性检查,我尝试直接在 Chrome 终端中运行代码,结果与 React 应用程序相同

发生什么事了? 🤔

javascript node.js regex browser
1个回答
0
投票

好吧...这似乎是因为

RegExpStringIterator
在浏览器中的工作方式与在 Node.js 中的工作方式不同。

我复制了来自 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll 的示例通过将结果传播到数组中:

  const regex = /(\*\*\*|___|\*\*|\*|__|\[.*?\]\([^)]*\))(.*?)(\1|$)/g;

  const matches = [...markdown.matchAll(regex)];

这在浏览器中的行为似乎与在节点中的行为相同✌️

© www.soinside.com 2019 - 2024. All rights reserved.