Created
July 18, 2013 05:19
-
-
Save GongLe/6026875 to your computer and use it in GitHub Desktop.
javascript基于扩充String对象原型的格式化字符串方法.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 扩充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