Created
October 18, 2020 20:53
-
-
Save hawkeye64/0ac691dce795752469cfca5619af1ad8 to your computer and use it in GitHub Desktop.
Formatted output like: print("Hello, {0}! The answer is {1}.", "World", 42);
This file contains hidden or 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
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