String formatter

Here’s a basic string formatter that takes in a format string and a variable number of arguments:

// Format string may contain variable references in the form "{i}"
// where i is the variable index
function format(fmt) {
    return fmt.replace(/\{(\d+)\}/g, function (s, i) {
        return arguments[i];
    });
}

// Usage:

var usercnt = 45, groupcnt = 3;

format("Found {1} users and {2} groups", usercnt, groupcnt);
// Returns "Found 45 users and 3 groups"

Similarly, object property names could be used:

// Format string may contain variable references in the form "{n}"
// where n is the variable name
function format(fmt, object) {
    return fmt.replace(/\{(\w+)\}/g, function (s, n) {
        return object[n];
    });
}

// Usage:

var results = {
    usercnt: 45,
    groupcnt: 3
};

format("Found {usercnt} users and {groupcnt} groups", results);
// Returns "Found 45 users and 3 groups"