Convert a string to a template string

前端 未结 19 2405
轮回少年
轮回少年 2020-11-22 08:30

Is it possible to create a template string as a usual string

let a=\"b:${b}\";

an then convert it into a template string

le         


        
19条回答
  •  臣服心动
    2020-11-22 09:31

    In my project I've created something like this with ES6:

    String.prototype.interpolate = function(params) {
      const names = Object.keys(params);
      const vals = Object.values(params);
      return new Function(...names, `return \`${this}\`;`)(...vals);
    }
    
    const template = 'Example text: ${text}';
    const result = template.interpolate({
      text: 'Foo Boo'
    });
    console.log(result);

    UPDATE I've removed lodash dependency, ES6 has equivalent methods to get keys and values.

提交回复
热议问题