What is the use of $1, $2, … etc in regex?
$1, $2 refers the capturing groups.
$1 means first capturing group
$2 means first capturing group
…. etc.
These are mainly used for replacement. Lets see an example
We have a string "We should learn"
and we want to replace the should
to will
.
var str1 = "We should learn";
var str2 = str1.replace( /(\w+) should (\w+)/, "$1 will $2" );
console.log(str1);
console.log(str2);
OUTPUT:
We should learn
We will learn
Explanation :
Through replace()
method we can replace some portions of a string with another string./(\w+) should (\w+)/
refers the actual string We should learn. There are two capturing groups (\w+)
, (\w+)
and in regex “$1 will $2
“ , $1
refers We and $2
refers learn. We replace We and learn as it is but change the word should to will.