1

Pardon me if it seems to be trivial but just to understand regexps: As said here with character (x) :

(x)           matches x and remembers 

First part "matches" I can understand but the second part "remembers" is a bit tedious for me to understand. Can someone please help in explaining it in much easier way?

nhahtdh
  • 54,546
  • 15
  • 119
  • 154
me_digvijay
  • 5,174
  • 7
  • 43
  • 81

2 Answers2

3

It's called capturing group. Using backreference ($1, $2, ...), you can reference it in the substitution string:

'R2D5'.replace(/(\d)/g, '$1$1')
// => "R22D55"

You can also use backreference (\1, \2, ...) in the pattern:

'ABBCCDEF'.match(/(.)\1/g)  // to match consecutive character
// => ["BB", "CC"]

And you will get additional parameters when you use replacement function:

'R2D5'.replace(/(\d)/g, function(fullMatch, capture1) {
    return (parseInt(capture1) + 1).toString();
})
// => "R3D6"
falsetru
  • 336,967
  • 57
  • 673
  • 597
0

In most regex stuff you can specify a "capturing group" and recall them later:

"something".replace(/so(me)/, '$1 ')

Here, the capturing group is (me) - the result will be me thing

phatskat
  • 1,755
  • 1
  • 15
  • 32