A tiny utility function for creating tagged template literals.
Download the CJS, ESM, UMD versions or install via NPM:
npm install @ryanmorr/tagged
Invoke with a function to handle the resulting template string:
const fn = tagged((str) => str + ' bar');
fn`foo`; //=> "foo bar"
Optionally provide a second function to mutate values passed to the tagged template:
const fn = tagged((str) => str, (val) => val.toLocaleDateString());
fn`The date is ${new Date()}`; //=> "The date is 07/06/2018"
Log to the console:
const log = tagged((msg) => console.log(msg));
log`This is an imporant message`;
Throw an error:
const error = tagged((msg) => {
throw new Error(msg);
});
const code = 404;
const msg = 'Not found';
error`Network error: ${code} ${msg}`;
Parse an HTML string into a document fragment:
const toDOM = tagged((html) => {
const template = document.createElement('template');
template.innerHTML = html;
return document.importNode(template.content, true);
});
const title = '<h1>Hello World</h1>';
const frag = toDOM`<div>${title}</div>`;
Compose regular expressions:
const regex = tagged((source) => new RegExp(source), (val) => val.source);
const yearRe = /([0-9]{4})/;
const monthRe = /([0-9]{2})/;
const dayRe = /([0-9]{2})/;
const dateRe = regex`^${yearRe}-${monthRe}-${dayRe}$`;
dateRe.test('2018-01-10'); //=> true
Encode parameters for a URI string:
const uri = tagged((str) => str, encodeURIComponent);
const genre = 'rock & roll';
const artist = 'led zeppelin';
uri`/genre/${genre}/artist/${artist}`); //=> "/genre/rock%20%26%20roll/artist/led%20zeppelin"
This project is dedicated to the public domain as described by the Unlicense.