Convert a string to a template string



  • 3 Answer(s)

    Here, the answer is not possible without dynamic code generation as the template string get reference to the runtime dynamic variable.

    Using eval:

    let tpl = eval('`'+a+'`');
    
    
    Answered on December 28, 2018.
    Add Comment

    Function that turns a regular string into a function providing a map of values, with template strings.

    Here, generating Template String Gist in the code sample:

    /**
    * Produces a function which uses template strings to do simple interpolation from objects.
    *
    * Usage:
    * var makeMeKing = generateTemplateString('${name} is now the king of ${country}!');
    *
    * console.log(makeMeKing({ name: 'Bryan', country: 'Scotland'}));
    * // Logs 'Bryan is now the king of Scotland!'
    */
    var generateTemplateString = (function(){
        var cache = {};
     
        function generateTemplate(template){
            var fn = cache[template];
     
            if (!fn){
                // Replace ${expressions} (etc) with ${map.expressions}.
     
                var sanitized = template
                    .replace(/\$\{([\s]*[^;\s\{]+[\s]*)\}/g, function(_, match){
                        return `\$\{map.${match.trim()}\}`;
                        })
                    // Afterwards, replace anything that's not ${map.expressions}' (etc) with a blank string.
                    .replace(/(\$\{(?!map\.)[^}]+\})/g, '');
                fn = Function('map', `return \`${sanitized}\``);
            }
     
            return fn;
        }
     
        return generateTemplate;
    })();
    

    Manipulating this as:

    var kingMaker = generateTemplateString('${name} is king!');
     
    console.log(kingMaker({name: 'Bryan'}));
    // Logs 'Bryan is king!' to the console.
    
    Answered on December 28, 2018.
    Add Comment

    Test this code snippet created 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);
    
    Answered on December 28, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.