Last Updated: March 21, 2023
·
232.2K
· avsej

Simple String.format() in javascript

String.prototype.format = function() {
  a = this;
  for (k in arguments) {
    a = a.replace("{" + k + "}", arguments[k])
  }
  return a
}

Usage:

console.log("Hello, {0}!".format("World"))

4 Responses
Add your response

Thanks! I made a small improvement so that all instances are replaced rather than just the first. :)

String.prototype.format = function () {
        var a = this;
        for (var k in arguments) {
            a = a.replace(new RegExp("\\{" + k + "\\}", 'g'), arguments[k]);
        }
        return a
    }
over 1 year ago ·

This doesn't change the problem of backward compatibility, but string literals are coming to JS:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

You might wish to amend your prototyping to match the functionality.

One thing to note is that it uses the ` string limiter rather than the single or double quotes ' "

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!")
over 1 year ago ·

Thanks, your post really helped me!

over 1 year ago ·