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
  • 55,989
  • 15
  • 126
  • 162
me_digvijay
  • 5,374
  • 9
  • 46
  • 83

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
  • 357,413
  • 63
  • 732
  • 636
  • 3
    And when using a function with `replace`, capture groups are the second (and on) arguments: `'R2D5'.replace(/(\d)/g, function(fullMatch, capture1) { ... })` – T.J. Crowder Dec 31 '14 at 15:47
  • @T.J.Crowder, Thank you for your comment. I updated the answer to mention it. – falsetru Dec 31 '14 at 15:50
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,797
  • 1
  • 15
  • 32