---
title: "JavaScript字符串格式化函数"
author: "deng131"
date: "2010-12-28T11:41:06Z"
tags: []
categories: ["Web前端"]
slug: "javascript"
draft: false
lastmod: "2011-04-04T12:13:50Z"
id: 853707
url: "https://thinking80s.iteye.com/blog/853707"
---

为了实现字符串模板，借鉴Extjs字符串格式化实现：

版本1：

```java
str = "abc:{name},cde:{code}";
String.prototype.format = function(obj){
if (arguments.length == 0) return '';
return this.replace(/\{[\w]*\}/g,function(match){
    return obj[match.replace(/^\{|\}$/g,'')] || "\'\'";
 });
}
str.format({name:'123',code:'456'}); // abc:123,cde:456
```


版本2：

```java
str = "abc:{0},cde:{1}";
String.format = function(str){
if (arguments.length == 0) return '';
var param = Array.prototype.slice.call(arguments,1);
  return str.replace(/\{[\w]*\}/g,function(match){
      return param[match.replace(/^\{|\}$/g,'')] || "\'\'";
  });
}
String.format(str,123,456); // abc:123,cde:456
```


版本3：

```java

str = "abc:{name},cde:{code}";
String.format = function(str,obj){
  if (arguments.length == 0) return '';
  return str.replace(/\{[\w]*\}/g,function(match){
      return obj[match.replace(/^\{|\}$/g,'')] || "\'\'";
  });
}
String.format(str,{name:123,code:456}); // abc:123,cde:456
```


上述3中都是通过正则表达式实现，

参考：
<http://mustache.github.com/>