如何在node.js中获得对regexp匹配索引的支持



我想使用regexp匹配返回的新索引属性。如下所述:https://v8.dev/features/regexp-match-indices

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

$ node --version
v14.6.0

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

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需要一点时间才能得到它,但它会发生的。(

最新更新