Skip to content

Instantly share code, notes, and snippets.

@GongLe
Created July 18, 2013 05:19
Show Gist options
  • Select an option

  • Save GongLe/6026875 to your computer and use it in GitHub Desktop.

Select an option

Save GongLe/6026875 to your computer and use it in GitHub Desktop.
javascript基于扩充String对象原型的格式化字符串方法.
/**
* 扩充String原型,字符串模板格式化
* <code>
* Array数据: '{0}'.format('hello world') ;
* json数据:'{name}'.format({'name':'hello world'});
* 输出结果:hello world
* </code>
* @author Gongle
* @date 2013年4月22日10:50:29
*/
String.prototype.format = function () {
var args = arguments;
if (Object.prototype.toString.call(args[0]) == '[object Object]') {
var _jsonData = args[0];
return this.replace(/{([^{}]+)}/gm, function (match, name) {
return typeof _jsonData[name] != 'undefined'
? _jsonData[name]
: match;
});
}
return this.replace(/{(\d+)}/g, function (match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment