Say I have template literal like so:
const templateLiteral = `string text ${expression} string text`
I want to dynamically evaluate the template literal into a finished string.
function toFoo(templateLiteral){
//returns "string text Foo string text"
return templateLiteral.evaluate('Foo');
}
function toBar(templateLiteral){
//returns "string text Bar string text"
return templateLiteral.evaluate('Bar');
}
function toBaz(templateLiteral){
//returns "string text Baz string text"
return templateLiteral.evaluate('Baz');
}
is there a way to do something like this with template literals, or am I just being dumb? (template.evaluate() is a made up function, but I am looking for that kind of functionality with JS!).
A placeholder is represented by ${} , with anything within the curly brackets treated as JavaScript and anything outside the brackets treated as a string: const method = 'interpolation' const dynamicString = `This string is using ${method}.
Objects are created in the memory, Object literal is just a way to create an object, Template Literal is a string which can contain embedded expressions.
Template literals (template strings) allow you to use strings or embedded expressions in the form of a string. They are enclosed in backticks `` . For example, const name = 'Jack'; console.
Using the template literal for the HTML is definitely more readable by reducing the annoyance. Your string can span multiple lines. You don't have to escape quotation characters. You don't have to use the plus operator.
I assume the best way to do this is quite obvious, simply reverse the situation given by the question. You just need to wrap the template literals in a function, and then you will delay evaluation until you pass in the desired params. It's that simple.
function evaluteTemplateLiteral(bar){
return `foo ${bar} baz`;
}
now if you wanted to get fancier, you could create this:
function evaluateGeneric(vals, fn){
return fn.apply(null, vals);
}
and you would use the above like so:
evaluateGeneric(['brown','fox','cholo'], function(){
return `the quick ${arguments[0]} fox ${arguments[1]}`;
});
Tagged template strings could help in this scenario:
function toFoo(strings, ...values) {
console.log(strings[0]); // string text
console.log(strings[1]); // string text
console.log(values[0]); // <your-passed-expression>
// TODO: Do your manipulation
}
const val = toFoo`string text ${expression} string text`;
strings
contains the "normal" tokens of the line and values
are the "variable" parts. Please note that you have to concatenate the string manually.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With