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
  • 10,467
  • 12
  • 39
  • 97
Peter
  • 110
  • 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
  • 67,185
  • 15
  • 124
  • 181