是否可以使用变量列表进行字符串插值?

时间:2018-08-30 06:20:52

标签: javascript

我知道您可以这样做:

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

但是这样的事情呢?

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

1 个答案:

答案 0 :(得分:1)

为传递的对象中的每个键构造一个全局正则表达式,并将其替换为其关联的值:

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