Joined November 2018
·

Chris_F

Posted to Simple String.format() in javascript over 1 year ago

Simple is nice, but it has its drawbacks.

console.log("{0} {1}".format("{1}", 42)) //oddly, prints "42 42"
//not sure how I would print "{0}" within the string without escaping...

Here's an implementation that validates the format string and allows escaping. I also prefer a free function over extending builtin types.

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!")
Achievements
1 Karma
0 Total ProTip Views