Skip to content
mckoss edited this page Sep 7, 2011 · 6 revisions

string.js - JavaScript string formatting

See string.js source code.

To use:

var string = require('org.startpad.string');

or

require('org.startpad.string').patch();

format(st, context, re)

Formats a string, using the context object (an Object or an Array). Template tags in the string (like {key}) are replaced with properties from the context object.

The following tag string are all valid:

"{0}" - The 0th element of an array context.
"{name}" - A named property in the passed context.
"{0.name}" - The name property in the 0th element of the context.
"{person.name}"
"{person.address.zip}"

If you want to use a different regular expression to match string tags, pass an alternate re value. The default one is:

/\{\s*([^} ]+)\s*\}/g;

patch()

Calling this function, will add a format method to the String.prototype whose calling signature is one of:

string.format(context)

or

string.format(arg0, arg1, arg2, ...)

The context must be an Object or Array type, or else type 2 is used, where each argument is associated with a numeric replacement tag in the string ({0}, {1}, etc.).

Clone this wiki locally