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?

3
  • 2
    string.replace('##name##', 'John Doe').replace('##date##', new Date()) and note replace() will return new string Commented Jul 11, 2018 at 8:22
  • You can use a regex. Commented Jul 11, 2018 at 8:23
  • I suggest using JavaScript Templating Engines eg mustache.js Commented Jul 11, 2018 at 8:27

1 Answer 1

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]));

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.