I came across the String interpolation feature in ES6. It works if I define the raw string in the code. But I want to read the raw string from a file and then replace the placeholders. How to do it?
file.txt
hello ${customer.name}
Node JS
var customer = {name: 'sid'};
var data = fs.readFileSync("file.txt","utf8");
// what should go here so that data is 'Hello sid'?
String interpolation is a new feature of ES6, that can make multi-line strings without the need for an escape character. We can use apostrophes and quotes easily that they can make our strings and therefore our code easier to read as well.
String interpolation in JavaScript is a process in which an expression is inserted or placed in the string. To insert or embed this expression into the string a template literal is used. By using string interpolation in JavaScript, values like variables and mathematical expressions and calculations can also be added.
$ is simply a valid JavaScript identifier. JavaScript allows upper and lower letters, numbers, and $ and _ . The $ was intended to be used for machine-generated variables (such as $0001 ). Prototype, jQuery, and most javascript libraries use the $ as the primary base object (or function).
In that case, the template literal is passed to your tag function, where you can then perform whatever operations you want on the different parts of the template literal. To escape a backtick in a template literal, put a backslash ( \ ) before the backtick. Dollar signs can be escaped as well to prevent interpolation.
You can build a one-liner instead of loading a template engine. This will replace ${field} with values from an object.
var obj = {a: 'one', b: 'two'};
var templ = '${a}, ${b}';
templ.replace(/\${([^}]*)}/g, (r,k)=>obj[k]);
// 'one, two'
I decided to go with es6-template-strings
as it seems straight forward. Alternatively, handlebar is also good for complex expressions.Petr's suggestion to use eval
also works but I have some constraints using eval
for my project
var data = fs.readFileSync("file.txt","utf8");
var compiled = compile(data);
var content = resolveToString(compiled, customer);
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