Skip to content

Instantly share code, notes, and snippets.

@blixt
Created September 27, 2015 15:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blixt/498cac8edcb77db3a701 to your computer and use it in GitHub Desktop.
Save blixt/498cac8edcb77db3a701 to your computer and use it in GitHub Desktop.
Formatting templating strings in ES6
function format(strings, ...values) {
const pieces = [];
for (let [index, string] of strings.entries()) {
let value = values[index];
const formatIndex = string.lastIndexOf('$');
if (formatIndex != -1) {
const format = string.substr(formatIndex + 1);
string = string.substr(0, formatIndex);
// TODO: Use an actual format engine here.
switch (format) {
case '02d':
if (value < 10) value = '0' + value;
break;
case 'json':
value = JSON.stringify(value);
break;
}
}
pieces.push(string);
if (value !== undefined) pieces.push(value);
}
return pieces.join('');
}
const person = {name: 'Lisa', occupation: 'Engineer'};
console.log(format`${person.name}'s information: $json${person}`);
// -> Lisa's information: {"name":"Lisa","occupation":"Engineer"}
const minutes = 3, seconds = 47;
console.log(format`The eggs will be ready in $02d${minutes}:$02d${seconds}.`);
// -> The eggs will be ready in 03:47.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment