Skip to content

Instantly share code, notes, and snippets.

@hawkeye64
Created October 18, 2020 20:53
Show Gist options
  • Save hawkeye64/0ac691dce795752469cfca5619af1ad8 to your computer and use it in GitHub Desktop.
Save hawkeye64/0ac691dce795752469cfca5619af1ad8 to your computer and use it in GitHub Desktop.
Formatted output like: print("Hello, {0}! The answer is {1}.", "World", 42);
function format(fmt, ...args) {
if (!fmt.match(/^(?:(?:(?:[^{}]|(?:\{\{)|(?:\}\}))+)|(?:\{[0-9]+\}))+$/)) {
throw new Error('invalid format string.');
}
return fmt.replace(/((?:[^{}]|(?:\{\{)|(?:\}\}))+)|(?:\{([0-9]+)\})/g, (m, str, index) => {
if (str) {
return str.replace(/(?:{{)|(?:}})/g, m => m[0]);
} else {
if (index >= args.length) {
throw new Error('argument index is out of range in format');
}
return args[index];
}
});
}
function print(fmt, ...args) {
console.log(format(fmt, ...args));
}
print("Hello, {0}! The answer is {1}.", "World", 42);
print("{0} {1}", "{1}", 42);
print("{{0}} will be replaced with {0}", 42);
print("{0}} woops, throw!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment