我知道您可以这样做:
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}));
答案 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}));