---
title: "[ExtJS3.2源码每天一小时]ExtJS中String类型的模板格式化（十一）"
author: "ting570732"
date: "2010-09-21T14:25:57Z"
tags: []
categories: ["Web前端"]
slug: "extjs3-2-extjs-string"
draft: false
lastmod: "2010-09-21T14:27:41Z"
id: 769063
url: "https://liust1987.iteye.com/blog/769063"
---

ExtJS对String类型扩展了格式化方法：

```java

//format 指定格式
format : function(format){
        //取出函数的参数，从1开始截取，就是去除掉format这个参数
        var args = Ext.toArray(arguments, 1);
        //替换掉格式串中的占位符 {0}，{1}等 m代表匹配项 i代表匹配项的下标
        return format.replace(/\{(\d+)\}/g, function(m, i){
            return args[i];
        });
}
//注意：这个方法是直接加到String类上的，而非String的prototype上。与Function的扩展是不同的。为什么要使用这样的方式呢？因为在使用function的扩展时，我们是在已有的function对象的基础上去创建其他的对象，例如回调函数、延迟函数等。但是String来说，他不需要现有对象，直接类似于一种静态方法，传入模板串，再传入对应的占位符参数就可以了。

```


例子：

```java


var result = Stirng.format("hello {0},today is {1}","Tom","Monday");

//那么result得到的值就是hello Tom，today is Monday。


```



//如果说我们要根据现有的模板格式串来生成字符串，我们就要根据Ext对String的扩展，自己写一个方法了。例如：


```java

//扩展
Ext.apply(String.prototype, {
    format : function(){
        var args = Ext.toArray(arguments);
        return this.replace(/\{(\d+)\}/g, function(m, i){
            return args[i];
        });
    }
});
//例子：
var tpl = "hello {0},today is {1}";

var result = tpl.format("Tom","Monday");

//那么result得到的值就是hello Tom，today is Monday。
//这种机制类似于Ext的Templete（模板），后面的博文会详细介绍Ext的Templete

```