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
  • 52,949
  • 15
  • 113
  • 149
me_digvijay
  • 5,087
  • 5
  • 41
  • 78

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
  • 314,667
  • 49
  • 610
  • 551
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,703
  • 15
  • 32