Skip to content

Instantly share code, notes, and snippets.

@coltrane
Last active January 16, 2017 20:29
Show Gist options
  • Save coltrane/b15f1e0db7ddb799f5ddadc7cca095a8 to your computer and use it in GitHub Desktop.
Save coltrane/b15f1e0db7ddb799f5ddadc7cca095a8 to your computer and use it in GitHub Desktop.
simple dynamic string templating for js that follows the syntax of es6 template literals
const rxTemplateSubst = /\\?\${([^}]*)}/g;
function template(str, substitutions) {
if(!str) return str;
return str.replace(rxTemplateSubst, (token, name) => {
if(token[0] === '\\') return token.substr(1);
return String(substitutions[name]);
});
}
// simple replacements...
console.log(
template("here is a ${what}, please send your comments to ${who}.", { what: "thingy", who: "mom" }));
// escapes...
console.log(
template("this one here is \\${escaped}, so it won't be replaced", {}));
// numbered/positional replacements...
function format(str, ...substitutions) {
return template(str, substitutions);
}
console.log(
format("here is a ${0} that I want you to ${1} ${2} times", "comment", "read", 5));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment