-2

I have a string, where I want to replace global myObj.value with myObj.name. I tried to construct a new RegExp object, but how to pass the square brackets ?

let param = {
  name: '[year]',
  value: '2019'
}

let str = 'Enter the number of days during [year] (they should not be more than your total days spent 
           during [year])'

I tried:

 str.replace(new RegExp('param.name', 'g'), param.value);

and

str.replace(new RegExp(`\\[param.name\\]`, 'g'), param.value)
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563

1 Answers1

0

You can escape regex special characters in your 'name' parameter by using a custom function to do that. Below is a sample with a custom function to replace special regex characters obtained from How to escape regular expression special characters using javascript?.

let param = {
  name: '[year]',
  value: '2019'
}

let str = 'Enter the number of days during [year] (they should not be more than your total days spent during [year])'

function escapeRegExp(text) {
  return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}

alert(str);

str = str.replace(new RegExp(escapeRegExp(param.name), 'g'), param.value);

alert(str);
nvkrj
  • 1,002
  • 1
  • 7
  • 17