-2

I have an object with tow properties and string, where I have the object name. I want to change object name with object value global, but not working.

let obj = {
  name: 'year',
  value: '2020',
};

let str = 'year year';

str.replace(/obj.name/g, obj.value);
jOE
  • 64
  • 8
  • Alternatively, use [`str.replaceAll(obj.name, obj.value)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll). – Sebastian Simon Oct 10 '20 at 08:17

1 Answers1

0

Variables aren't expanded inside regexp literals. You need to construct the regexp dynamically.

let obj = {
  name: 'year',
  value: '2020',
};

let str = 'year year';
console.log(str.replace(new RegExp(obj.name, 'g'), obj.value));
Barmar
  • 741,623
  • 53
  • 500
  • 612