how to get support for regexp-match-indices in node.js?

Viewed 78

I want to use the new indices property returned by a regexp match. It is described here: https://v8.dev/features/regexp-match-indices

I have upgraded to the latest version of node.js:

$ node --version
v14.6.0

But when I run the sample code, the .match method return value does not contain an indices property.

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');

1 Answers

As of this writing (July 2020), the feature is behind the --harmony-regexp-match-indices flag. Launch Node.js 14.6.0 with that flag, and you will have access to the indices property.

You can track the feature at https://github.com/tc39/proposal-regexp-match-indices#todo where you will see it says that V8 still has the feature behind the flag. (Once V8 releases it unflagged, it will take a little time before Node.js gets it, but it will happen.)

Related