node.js - 如何在node.js中获得对regexp-match-indices的支持?

标签 node.js regex

我想使用正则表达式匹配返回的新索引属性。这里描述的是: https://v8.dev/features/regexp-match-indices

我已经升级到最新版本的node.js:

$ node --version
v14.6.0

但是当我运行示例代码时,.match 方法返回值不包含索引属性。

function displayError(text, message)
{
  const re = /\b(continue|function|break|for|if)\b/;
  const match = text.match(re);

  // Index `1` corresponds to the first capture group.
  const [start, end] = match.indices[1];
  
  const error = ' '.repeat(start) + // Adjust the caret position.
    '^' +
    '-'.repeat(end - start - 1) +   // Append the underline.
    ' ' + message;                  // Append the message.
  console.log(text);
  console.log(error);
}

const code = 'const function = foo;'; // faulty code
displayError(code, 'Invalid variable name');

最佳答案

截至撰写本文时(2020 年 7 月),该功能位于 --harmony-regexp-match-indices 标志后面。使用该标志启动 Node.js 14.6.0,您将可以访问 indices 属性。

您可以通过 https://github.com/tc39/proposal-regexp-match-indices#todo 跟踪该功能你会看到它说 V8 仍然具有该标志背后的功能。 (一旦 V8 未标记地释放它,Node.js 需要一点时间才能获取它,但它会发生。)

关于node.js - 如何在node.js中获得对regexp-match-indices的支持?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63141385/

相关文章:

python - 正则表达式 - `^`、 `$` 和 `\A`、 `\Z` 之间的差异

node.js - 在没有端口映射的情况下运行 Node Docker

node.js - sequelize.js 创建 db 表时,表行有没有限制?

javascript - Adobe Brackets Live Preview 无法访问 Node.js 服务器

regex - Notepad++:为时间戳添加括号

python - 如何使用 Python 从一行文本中过滤掉表达式?

javascript - 如何在 cucumber.js 的 AfterStep 钩子(Hook)中获取步骤结果

node.js - 当我尝试在环回 (strongloop) web 应用程序中安装依赖项时出现 Npm 错误

ruby - 给定格式化文件名的正则表达式匹配某些条件?

regex - 棘手的 htaccess 重定向使用子文件夹的通配符