String.format Function
Replaces each format item in a String object with the text equivalent of a corresponding object's value.
var s = String.format(format, args);
Arguments
format
A format string.args
An array of objects to format.
Return Value
A copy of the string with the formatting applied.
Exceptions
Exception type |
Condition |
---|---|
(Debug) format contains a mismatched opening or closing brace. |
Remarks
Use the format function to replace specified format items with the text representation of the corresponding object values. The args argument can contain a single object or an array of objects. The format argument contains zero or more runs of fixed text intermixed with one or more format items. Each format item corresponds to an object in objects. At run time, each format item is replaced by the string representation of the corresponding object in the list.
Format items consist of a number enclosed in braces, such as {0}, that identifies a corresponding item in the objects list. Numbering starts with zero. To specify a single literal brace character in format, specify two leading or trailing brace characters; that is, "{{" or "}}". Nested braces are not supported.
Specifying a Custom Formatting Routine
You can specify a custom formatting routine for a format item by providing a special formatting object that has a toFormattedString method in the args argument. The toFormattedString method must accept a string argument and return a string. At run time, the format function passes any string in the braces of its corresponding parameter specifier to the toFormattedStrings method. The string returned by the toFormattedString method is inserted into formatted string at the location of the corresponding parameter specifier.
Example
The following example shows how to use the format function to replace specified format items with the text representation of the corresponding object values. The code includes an example of a custom formatting object that has a toFormattedString method.
// Define an class with a custom toFormattedString
// formatting routine.
Type.registerNamespace('Samples');
Samples.ToFormattedStringExample = function() {
}
Samples.ToFormattedStringExample.prototype = {
toFormattedString: function(format) {
return "This was custom formatted: " + format;
}
}
Samples.ToFormattedStringExample.registerClass('Samples.ToFormattedStringExample');
var result = "";
// Format a string.
result = String.format("{0:d}", 123);
// Displays: "123"
alert(result);
// Format a string with an object that has
// a custom toFormattedString method.
var o = new Samples.ToFormattedStringExample();
result = String.format("{0:12345}", o);
// Displays: "This was custom formatted: 12345"
alert(result);