Skip to content

Instantly share code, notes, and snippets.

@danny-andrews
Last active October 5, 2017 16:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danny-andrews/ff665e023da5cd19dc65527bbb896616 to your computer and use it in GitHub Desktop.
Save danny-andrews/ff665e023da5cd19dc65527bbb896616 to your computer and use it in GitHub Desktop.
Poor-man's printf
// Named replacements!
const formatString = (string, substitutions = {}) =>
string.replace(
/%{([^}]+)}/g,
(match, id) => {
return substitutions.hasOwnProperty(id) ? substitutions[id] : match
}
);
formatString('%{noun} is %{adjective}', {
noun: 'my dad',
adjective: 'the best'
}); // Prints "my dad is the best"
// https://stackoverflow.com/a/4673436
const formatString = (string, ...args) =>
string.replace(
/{(\d+)}/g,
(match, number) =>
typeof args[number] !== 'undefined' ? args[number] : match
)
// Even poorer (adapted from: https://github.com/mjackson/expect/blob/ef4aa90/modules/assert.js#L3)
const formatString = (string, args) => string.replace(
/%s/g,
(match, number) => typeof args[number] !== 'undefined' ? args[number] : match
);
// GET RICH QUICK!!! https://github.com/alexei/sprintf.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment