Muhammad Umer
Muhammad Umer

Reputation: 18169

Is it possible to do string interpolation with list of variables?

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

Upvotes: 0

Views: 257

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371203

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

Upvotes: 1

Related Questions