Replace string value with javascript object

前端 未结 4 538
清酒与你
清酒与你 2021-01-05 16:43

I am currently making a small module for NodeJs. For which I need a small help.

I will tell it like this. I have a variable with string. It contains a string html va

4条回答
  •  迷失自我
    2021-01-05 17:19

    Since you are using ES6 template string you can use a feature called 'tagged template strings'. Using tagged template strings you are allowed to modify the output of a template string. You create tagged template string by putting a 'tag' in front of the template string, the 'tag' is a reference to a method that will receive the string parts in a list as the first argument and the interpolation values as remaining arguments. The MDN page on template strings already provides an example template string 'tag' that we can use:

    function template(strings, ...keys) {
      return (function(...values) {
        var dict = values[values.length - 1] || {};
        var result = [strings[0]];
        keys.forEach(function(key, i) {
          var value = Number.isInteger(key) ? values[key] : dict[key];
          result.push(value, strings[i + 1]);
        });
        return result.join('');
     });
    }
    

    You use the 'tag' by calling:

    var tagged = template`
    
    
       
      Document ${'title'}
    
    
    
      

    Test file, ${'text'}

    `;

    Notice that interpolation of variables uses the syntax ${'key'} instead of $(key). You can now call the produced function to get the desired result:

    tagged({ "title" : "my title", "text" : "text is this" });
    

    Run the code example on es6console

提交回复
热议问题