easy-template-string
v1.0.1
Published
Allow normal JS strings to behave like template strings
Downloads
495
Readme
easy-template-string
Allow normal JS strings to behave like template strings
Usage
const Template = require('easy-template-string').default;
const template1 = new Template('x${first}y${second}z');
console.log(template1.interpolate({ first: 'abc', second: 'def' })); // xabcydefz
If a key is missing in the object passed to interpolate
, it will simply be ignored in the output:
const template2 = new Template('x${value1}y${value2}z');
console.log(template2.interpolate({ value2: 'def' })); // xydefz
Patterns can be escaped using a backslash (\
). Note that, in simple string initialisation, this requires escaping the backslash itself:
const template3 = new Template('x\\${escaped}y');
console.log(template3.template); // x\${escaped}y
console.log(template3.interpolate({ escaped: 'abc' })); // x${escaped}y
Values will always be coerced to a string, even if that isn't pretty:
const template4 = new Template('x${notPretty}y${pretty}z');
console.log(template4.interpolate({ notPretty: {}, pretty: 'def' })); // x[object Object]ydefz
But undefined
will be ignored just like a missing property.
Provides a helper method to check for a Template string:
console.log(Template.isTemplate('x${value1}y${value2}z')); // true
console.log(Template.isTemplate('x\\${escaped}y')); // false
console.log(Template.isTemplate('just a string')); // false
Restrictions
Requires Node v12.0.0+ to support string.prototype.matchAll
.