主要代码 if (!String.prototype.format) { String.prototype.format = function() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return this.replace(/\{(\d)\}/g, function(s, i) { return args[i]; }); }; } 测试代码 function clickEvent() { var formatStr = "{0} {1} {2}"; var a = "Hello", b = "World", c = "!"; var str = formatStr.format(a, b, c); $('#result').val(str); } 格式化 结果
if (!String.prototype.format) { String.prototype.format = function() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return this.replace(/\{(\d)\}/g, function(s, i) { return args[i]; }); }; }
function clickEvent() { var formatStr = "{0} {1} {2}"; var a = "Hello", b = "World", c = "!"; var str = formatStr.format(a, b, c); $('#result').val(str); }
在Javascript中对字符串进行格式化的方法