Skip to content

Instantly share code, notes, and snippets.

@danny-andrews

danny-andrews/printf.js

Last active Oct 5, 2017
Embed
What would you like to do?
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