easy-template-string
TypeScript icon, indicating that this package has built-in type declarations

1.0.1 • Public • Published

easy-template-string

Build Status Dependency Status Code Coverage

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.

Readme

Keywords

Package Sidebar

Install

npm i easy-template-string

Weekly Downloads

27

Version

1.0.1

License

ISC

Unpacked Size

6.32 kB

Total Files

5

Last publish

Collaborators

  • manolan