0

I'm trying to replace all these strings:

'Apples are {{appleColor}}'
'Oranges are {{orangeColor}}'
'My name is {{name}}'

With these:

obj = {
  appleColor: 'red',
  orangeColor: 'orange',
  name: 'Todd'
}

Thanks in advance!

3
  • You can do this is most browsers today with template strings in plain JS using ${} Commented Dec 30, 2016 at 22:24
  • 2
    You're trying to? So what have you tried? OR do you mean you want to? Commented Dec 30, 2016 at 22:24
  • mustache.js does this exact thing and more Commented Dec 30, 2016 at 22:28

1 Answer 1

8

Simple solution using String.prototype.replace() function with replacement callback:

var str = "'Apples are {{appleColor}}', 'Oranges are {{orangeColor}}', 'My name is {{name}}' ",
    obj = {
        appleColor: 'red',
        orangeColor: 'orange',
        name: 'Todd'
    };

str = str.replace(/{{(\w+)}}/g, function (m, m1) {
  return obj[m1] || m;  
});

console.log(str);

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

2 Comments

there are a few caveats worth mentioning with this approach; error handling reveals data names, "toString" et al conflicts, nest snafu, only wordy key names (no _ or $ support), no object path depth, etc.
@dandavis, As I wrote Simple solution ... for simple cases )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.