0

How can I replace values from a string like that:

// "Hello ##name##, today is ##date##"

It's possible like that:

    var string = "Hello ##name##, today is ##date##"
    console.log(string.replace('##name##', 'John Doe'));

But how replace the ##date##too, and build the string again?

Isaac
  • 12,042
  • 16
  • 52
  • 116
Peter
  • 120
  • 1
  • 2
  • 12

1 Answers1

8

You would use a regex and pass a function as a second argument:

var string = "Hello ##name##, today is ##date##";
const map = {name: 'Foo', date: 'bar'};

console.log(string.replace(/##(\w+)##/g, (_,m) => map[m]));
baao
  • 71,625
  • 17
  • 143
  • 203