我想使用正则表达式匹配返回的新索引属性。这里描述的是: 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/