0

I know you can do this:

let a = 'building'; console.log(`it's a tall ${a}`); 

But what about something like this:

let b = 'building'; let text = 'it's a tall $x`; console.log(text.interpolate({x: b})); 
2

1 Answer 1

1

Construct a global regular expression for each key in the passed object, and replace it with its associated value:

function escapeRegExp(string) { // https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } let a = 'foo'; let b = 'building'; let text = "$y $y it's a tall $x $y"; const interpolate = (input, obj) => Object.entries(obj).reduce((a, [key, replaceStr]) => ( a.replace(new RegExp(escapeRegExp('$' + key), 'g'), replaceStr) ), input); console.log(interpolate(text, {x: b, y: a}));

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.