String.format 函数

更新:2007 年 11 月

String 对象中的每个格式项替换为相应对象值的文本等效项。

var s = String.format(format, args);

参数

  • format
    格式字符串。

  • args
    要设置其格式的对象的数组。

返回值

具有所应用格式设置的字符串副本。

异常

异常类型

条件

Sys.ArgumentException

(调试)format 包含不匹配的左大括号或右大括号。

备注

使用 format 函数可以用相应对象值的文本表示形式替换指定的格式项。args 参数可以包含单个对象或对象数组。format 参数由零个或多个固定文本序列与一个或多个格式项混和组成。每个格式项都对应于 objects 中的一个对象。在运行时,每个格式项都由列表中相应对象的字符串表示形式替换。

格式项包含一个用大括号括起来的编号(如 {0}),该编号标识 objects 列表中的一个相应项。编号从零开始。若要在 format 中指定单个大括号字符,请指定两个前导或尾随大括号字符,即“{{”或“}}”。不支持嵌套大括号。

指定自定义格式设置例程

通过在 args 参数中提供一个具有 toFormattedString 方法的特殊格式设置对象,可以为格式项指定自定义格式设置例程。toFormattedString 方法必须接受一个字符串参数并返回一个字符串。在运行时,format 函数将括在其相应参数说明符的大括号中的任何字符串都传递给 toFormattedStrings 方法。toFormattedString 方法返回的字符串将插入到格式化字符串中相应参数说明符的位置处。

示例

下面的示例演示如何使用 format 函数将指定的格式项替换为相应对象值的文本表示形式。代码包含一个自定义格式设置对象示例,该对象具有一个 toFormattedString 方法。

// 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);

请参见

参考

String.startsWith 函数

其他资源

语言参考