Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 String interpolation from file content

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'?
like image 519
sidgate Avatar asked Sep 20 '16 01:09

sidgate


People also ask

What is string interpolation in ES6?

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.

How do you do string interpolation in JavaScript?

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.

What is `$ in JavaScript?

$ 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).

How do you write backticks in JavaScript?

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.


2 Answers

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'
like image 182
John Williams Avatar answered Sep 19 '22 13:09

John Williams


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);
like image 22
sidgate Avatar answered Sep 20 '22 13:09

sidgate