How would you turn a JavaScript variable into a Template literal?

后端 未结 4 1350
走了就别回头了
走了就别回头了 2020-11-30 15:32

I would like to take text that I generated and stored in a string and use it like a template literal.

var generatedText = \"Pretend this text was generated          


        
4条回答
  •  旧巷少年郎
    2020-11-30 16:03

    The interpolate function below is an extended version of this answer that adds support for simple nested object field references (e.g.: a.b.c)

    function interpolate(s, obj) {
      return s.replace(/[$]{([^}]+)}/g, function(_, path) {
        const properties = path.split('.');
        return properties.reduce((prev, curr) => prev && prev[curr], obj);
      })
    }
    
    console.log(interpolate('hello ${a.b.c}', {a: {b: {c: 'world'}}}));
    // Displays 'hello world'

提交回复
热议问题