0x0 方案

String.prototype.interpolate = function (params = {}) {
    const names = Object.keys(params);
    const vals = Object.values(params);
    return new Function(...names, `return \`${this}\`;`)(...vals);
}

0x1 使用方法

const template = 'Example text: ${text}';

const result = template.interpolate({
  text: 'Hello'
});

console.log(result);
// Example text: Hello
console.log(typeof result);
// string

0x2 补充说明

如同使用eval()一样,不是严格安全的。

文章作者: Blink Chen
版权声明: 本站所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 kingcyk's Blog
技术活儿 JavaScript
喜欢就支持一下吧