2

I would like to replace a string in another string. My problem is, that the search-string is a variable and I need to set a group for this, because I want to reuse the original matching string.

const string = 'Any string with many words'
const label = 'any'
const re = new RegExp(label, 'gi')

string = string.replace(
    re,
    '>>>' + $1 + '<<<'
)

console.log(string)
// Expect: >>>Any<<< string with m>>>any<<< words
user3142695
  • 15,844
  • 47
  • 176
  • 332

1 Answers1

1

You need to use a backreference inside a string replacement pattern. Also, to access the whole match value, you need to use $& backreference, not $1. The $1 backreference will work of you use parentheses around the whole pattern (like new RegExp(`(${label})`, 'gi')), but you do not need that since there is a convenient $& backreference. See Specifying a string as a parameter.

let string = 'Any string with many words';
const label = 'any';
const re = new RegExp(label, 'gi');

string = string.replace(
    re,
    '>>>$&<<<'
)

console.log(string)

Note that string should not be declared as const if you need to modify its value (I used let above).

Note, that if your label contains special regex chars, it is a good idea to escape the label value.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563