RegExp.$1 is deprecated, how to replace it with regexp.test(str)

Viewed 28

Now that the $1, $2, .... from RegExp are deprecated you should do something like the following

'John Smith'.replace(/(\w+)\s(\w+)/, '$2, $1');

But I ran into the following code (a bit modified for the purpose of this question)

const name = 'John Smith';
if (/(\w+)\s(\w+)/.test(name)) {
    console.log(RegExp.$1)
}

How would I access these variables in this situation? Should I run the RegExp again like this

if (/(\w+)\s(\w+)/.test(name)) {
    console.log(name.match(/(\w+)\s(\w+)/)[1]);
}

Doesn't look like an improvement to me.

0 Answers
Related