Allow normal JS strings to behave like template strings

Usage no npm install needed!

<script type="module">
  import easyTemplateString from 'https://cdn.skypack.dev/easy-template-string';



Build Status Dependency Status Code Coverage

Allow normal JS strings to behave like template strings


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


Requires Node v12.0.0+ to support string.prototype.matchAll.