Last active
October 5, 2017 16:35
-
-
Save danny-andrews/ff665e023da5cd19dc65527bbb896616 to your computer and use it in GitHub Desktop.
Poor-man's printf
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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