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
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