Navin Rauniyar
Navin Rauniyar

Reputation: 10525

replacement using function instead of regex

I found the following code in a book:

Previous example:

'iixxxixx'.replace(/i+/g,'($1)')

Next example:

You can also compute a replacement via a function:

function repl(all){
  return '('+all.toUpperCase()+')'
}
'axbbyyxaa'.repl(/a+|b+/g,replacement)
//logs ' (A) x (BB) yyx (AA) '

replacement may be like ($1)

But when I tested it is returning undefined is not a function.

I think something missing, what is the correct way to do?

Upvotes: 0

Views: 36

Answers (1)

Tomalak
Tomalak

Reputation: 338208

I'm pretty sure your book says

function repl(all){
  return '(' + all.toUpperCase() + ')';
}

'axbbyyxaa'.replace(/a+|b+/g, repl);

//logs '(A)x(BB)yyx(AA)'

Upvotes: 1

Related Questions