我正在寻找一个很好的JavaScript等价的C/PHP printf()
或C#/ Java程序员String.Format()
(IFormatProvider
对于.NET).
我的基本要求是现在有一千个数字分隔符格式,但处理许多组合(包括日期)的东西会很好.
我意识到Microsoft的Ajax库提供了一个版本String.Format()
,但我们不希望该框架的整个开销.
基于之前建议的解决方案:
// First, checks if it isn't implemented yet.
if (!String.prototype.format) {
String.prototype.format = function() {
var args = arguments;
return this.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
}
"{0} is dead, but {1} is alive! {0} {2}".format("ASP", "ASP.NET")
输出
ASP已经死了,但ASP.NET还活着!ASP {2}
如果你不想修改String
原型:
if (!String.format) {
String.format = function(format) {
var args = Array.prototype.slice.call(arguments, 1);
return format.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
}
给你更熟悉的东西:
String.format('{0} is dead, but {1} is alive! {0} {2}', 'ASP', 'ASP.NET');
结果相同:
ASP已经死了,但ASP.NET还活着!ASP {2}
从ES6开始,您可以使用模板字符串:
let soMany = 10; console.log(`This is ${soMany} times easier!`); // "This is 10 times easier!
有关详细信息,请参阅下面的Kim的答案.
试试用于JavaScript的sprintf().
如果你真的想自己做一个简单的格式化方法,不要连续进行替换,而是同时进行.
因为当前替换的替换字符串也包含如下格式序列时,提及的大多数其他提议都会失败:
"{0}{1}".format("{1}", "{0}")
通常你会期望输出是,{1}{0}
但实际输出是{1}{1}
.所以同时替换就像在恐惧症的建议中一样.
这很有趣,因为Stack Overflow实际上有一个String
叫做原型的格式化函数formatUnicorn
.试试吧!进入控制台并键入以下内容:
"Hello, {name}, are you feeling {adjective}?".formatUnicorn({name:"Gabriel", adjective: "OK"});
你得到这个输出:
Hello, Gabriel, are you feeling OK?
您可以使用对象,数组和字符串作为参数!我得到了它的代码并重新编写它以生成一个新版本String.prototype.format
:
String.prototype.formatUnicorn = String.prototype.formatUnicorn ||
function () {
"use strict";
var str = this.toString();
if (arguments.length) {
var t = typeof arguments[0];
var key;
var args = ("string" === t || "number" === t) ?
Array.prototype.slice.call(arguments)
: arguments[0];
for (key in args) {
str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
}
}
return str;
};
注意聪明的Array.prototype.slice.call(arguments)
调用 - 这意味着如果你抛出的是字符串或数字的参数,而不是单个JSON样式的对象,你String.Format
几乎可以完全获得C#的行为.
"a{0}bcd{1}ef".formatUnicorn("foo", "bar"); // yields "aFOObcdBARef"
那是因为Array
's slice
将强制arguments
进入一个Array
,无论它是否是原来的,并且key
将是每个数组元素的索引(0,1,2 ......)强制成一个字符串(例如,"0",所以"\\{0\\}"
为你的第一个正则表达式模式).
整齐.
我到了这个问题页面,希望找到如何在JavaScript中格式化数字,而不引入另一个库.这是我发现的:
sprintf("%.2f", num)
似乎是JavaScript中的等效num.toFixed(2)
格式,格式化num
为2位小数,带有舍入(但请参阅@ ars265关于Math.round
下面的注释).
(12.345).toFixed(2); // returns "12.35" (rounding!) (12.3).toFixed(2); // returns "12.30" (zero padding)
相当于sprintf("%.2e", num)
是num.toExponential(2)
.
(33333).toExponential(2); // "3.33e+4"
要在基数B中打印数字,请尝试num.toString(B)
.JavaScript支持自动转换到基数2到36(此外,某些浏览器对base64编码的支持有限).
(3735928559).toString(16); // to base 16: "deadbeef" parseInt("deadbeef", 16); // from base 16: 3735928559
关于JS数字格式的快速教程
toFixed()的Mozilla参考页面(带有指向toPrecision(),toExponential(),toLocaleString(),...的链接)
从ES6开始,您可以使用模板字符串:
let soMany = 10; console.log(`This is ${soMany} times easier!`); // "This is 10 times easier!
请注意,模板字符串被反引号 `而不是(单个)引号包围.
了解更多信息:
https://developers.google.com/web/updates/2015/01/ES6-Template-Strings
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings
注意:检查mozilla-site以查找支持的浏览器列表.
jsxt,Zippo
此选项更适合.
String.prototype.format = function() { var formatted = this; for (var i = 0; i < arguments.length; i++) { var regexp = new RegExp('\\{'+i+'\\}', 'gi'); formatted = formatted.replace(regexp, arguments[i]); } return formatted; };
使用此选项,我可以替换这些字符串:
'The {0} is dead. Don\'t code {0}. Code {1} that is open source!'.format('ASP', 'PHP');
使用您的代码,第二个{0}将不会被替换.;)
我用这个简单的功能:
String.prototype.format = function() { var formatted = this; for( var arg in arguments ) { formatted = formatted.replace("{" + arg + "}", arguments[arg]); } return formatted; };
这与string.format非常相似:
"{0} is dead, but {1} is alive!".format("ASP", "ASP.NET")
对于Node.js用户,util.format
它具有类似printf的功能:
util.format("%s world", "Hello")
我很惊讶没有人使用过reduce
,这是一个原生简洁而强大的JavaScript功能.
String.prototype.format = function() {
return [...arguments].reduce((p,c) => p.replace(/%s/,c), this);
};
console.log('Is that a %s or a %s?... No, it\'s %s!'.format('plane', 'bird', 'SOman'));
这是JavaScript中sprintf 的最小实现:它只执行"%s"和"%d",但是我留下了空间来扩展它.它对OP来说毫无用处,但其他偶然发现来自谷歌的人可能会从中受益.
function sprintf() { var args = arguments, string = args[0], i = 1; return string.replace(/%((%)|s|d)/g, function (m) { // m is the matched format, e.g. %s, %d var val = null; if (m[2]) { val = m[2]; } else { val = args[i]; // A switch statement so that the formatter can be extended. Default is %s switch (m) { case '%d': val = parseFloat(val); if (isNaN(val)) { val = 0; } break; } i++; } return val; }); }
例:
alert(sprintf('Latitude: %s, Longitude: %s, Count: %d', 41.847, -87.661, 'two')); // Expected output: Latitude: 41.847, Longitude: -87.661, Count: 0
与以往的答复类似的解决方案对比,这其中做了所有替代一气呵成,所以它不会取代先前所取代值的部分.
JavaScript程序员可以在https://github.com/ildar-shaimordanov/jsxt/blob/master/js/String.js上使用String.prototype.sprintf .以下是示例:
var d = new Date(); var dateStr = '%02d:%02d:%02d'.sprintf( d.getHours(), d.getMinutes(), d.getSeconds());
添加到zippoxer
答案,我使用此功能:
String.prototype.format = function () { var a = this, b; for (b in arguments) { a = a.replace(/%[a-z]/, arguments[b]); } return a; // Make chainable }; var s = 'Hello %s The magic number is %d.'; s.format('world!', 12); // Hello World! The magic number is 12.
我还有一个非原型版本,我经常使用它的类似Java的语法:
function format() { var a, b, c; a = arguments[0]; b = []; for(c = 1; c < arguments.length; c++){ b.push(arguments[c]); } for (c in b) { a = a.replace(/%[a-z]/, b[c]); } return a; } format('%d ducks, 55 %s', 12, 'cats'); // 12 ducks, 55 cats
ES 2015中所有酷炫的新东西都让这更容易:
function format(fmt, ...args){ return fmt .split("%%") .reduce((aggregate, chunk, i) => aggregate + chunk + (args[i] || ""), ""); } format("Hello %%! I ate %% apples today.", "World", 44); // "Hello World, I ate 44 apples today."
我认为,因为这与旧版本一样,实际上并不解析字母,所以也可以只使用一个令牌%%
.这具有显而易见的优点,并且不会使单个使用变得困难%
.但是,如果%%
由于某种原因需要,则需要将其替换为自身:
format("I love percentage signs! %%", "%%"); // "I love percentage signs! %%"
+1 Zippo除了函数体需要如下所示,否则它会在每次迭代时附加当前字符串:
String.prototype.format = function() { var formatted = this; for (var arg in arguments) { formatted = formatted.replace("{" + arg + "}", arguments[arg]); } return formatted; };
我想分享我对'问题'的解决方案.我没有重新发明轮子,但试图找到一个基于JavaScript已经做的解决方案.优点是,您可以免费获得所有隐式转换.设置String的prototype属性$提供了非常好的紧凑语法(参见下面的示例).它可能不是最有效的方式,但在大多数情况下处理输出它不必超级优化.
String.form = function(str, arr) { var i = -1; function callback(exp, p0, p1, p2, p3, p4) { if (exp=='%%') return '%'; if (arr[++i]===undefined) return undefined; exp = p2 ? parseInt(p2.substr(1)) : undefined; var base = p3 ? parseInt(p3.substr(1)) : undefined; var val; switch (p4) { case 's': val = arr[i]; break; case 'c': val = arr[i][0]; break; case 'f': val = parseFloat(arr[i]).toFixed(exp); break; case 'p': val = parseFloat(arr[i]).toPrecision(exp); break; case 'e': val = parseFloat(arr[i]).toExponential(exp); break; case 'x': val = parseInt(arr[i]).toString(base?base:16); break; case 'd': val = parseFloat(parseInt(arr[i], base?base:10).toPrecision(exp)).toFixed(0); break; } val = typeof(val)=='object' ? JSON.stringify(val) : val.toString(base); var sz = parseInt(p1); /* padding size */ var ch = p1 && p1[0]=='0' ? '0' : ' '; /* isnull? */ while (val.length这里有一些例子:
String.format("%s %s", [ "This is a string", 11 ]) console.log("%s %s".$("This is a string", 11)) var arr = [ "12.3", 13.6 ]; console.log("Array: %s".$(arr)); var obj = { test:"test", id:12 }; console.log("Object: %s".$(obj)); console.log("%c", "Test"); console.log("%5d".$(12)); // ' 12' console.log("%05d".$(12)); // '00012' console.log("%-5d".$(12)); // '12 ' console.log("%5.2d".$(123)); // ' 120' console.log("%5.2f".$(1.1)); // ' 1.10' console.log("%10.2e".$(1.1)); // ' 1.10e+0' console.log("%5.3p".$(1.12345)); // ' 1.12' console.log("%5x".$(45054)); // ' affe' console.log("%20#2x".$("45054")); // ' 1010111111111110' console.log("%6#2d".$("111")); // ' 7' console.log("%6#16d".$("affe")); // ' 45054'
15> Chris S..:我会添加自己的发现,因为我问过:
number_format(用于千位分隔符/货币格式)
sprintf(与上面的作者相同)
可悲的是,似乎sprintf没有像.NET的字符串格式那样处理千位分隔符格式.
16> 小智..:我使用一个名为String.format for JavaScript的小库,它支持大多数格式字符串功能(包括数字和日期的格式),并使用.NET语法.脚本本身小于4 kB,因此不会产生太多开销.
17> 小智..:十分优雅:
String.prototype.format = function (){ var args = arguments; return this.replace(/\{\{|\}\}|\{(\d+)\}/g, function (curlyBrack, index) { return ((curlyBrack == "{{") ? "{" : ((curlyBrack == "}}") ? "}" : args[index])); }); }; // Usage: "{0}{1}".format("{1}", "{0}")信用去
(断链)https://gist.github.com/0i0/1519811
18> 17 of 26..:如果您要处理千位分隔符,您应该使用JavaScript Number类中的toLocaleString(),因为它将格式化用户区域的字符串.
JavaScript Date类可以格式化本地化的日期和时间.
19> redestructa..:我用这个:
String.prototype.format = function() { var newStr = this, i = 0; while (/%s/.test(newStr)) newStr = newStr.replace("%s", arguments[i++]) return newStr; }然后我称之为:
"%s
%s
".format("Header", "Just a test!");
20> Thiago Mata..:我有一个非常接近彼得的解决方案,但它涉及数字和对象的情况.
if (!String.prototype.format) { String.prototype.format = function() { var args; args = arguments; if (args.length === 1 && args[0] !== null && typeof args[0] === 'object') { args = args[0]; } return this.replace(/{([^}]*)}/g, function(match, key) { return (typeof args[key] !== "undefined" ? args[key] : match); }); }; }也许处理所有深层次的情况可能更好,但是对于我的需求,这很好.
"This is an example from {name}".format({name:"Blaine"}); "This is an example from {0}".format("Blaine");PS:如果您在AngularJS等模板框架中使用翻译,这个功能非常酷:
{{('hello-message'|translate).format(user)}}
{{('hello-by-name'|translate).format( user ? user.name : 'You' )}}
en.json就像
{ "hello-message": "Hello {name}, welcome.", "hello-by-name": "Hello {0}, welcome." }
21> Spudley..:该PHPJS项目写JavaScript实现的许多PHP的功能.由于PHP的
sprintf()
功能与C基本相同printf()
,因此它们的JavaScript实现应满足您的需求.
22> 小智..:一个非常不同的版本,我喜欢的版本(这个版本使用{xxx}令牌而不是{0}编号的参数,这更加自我记录并且更适合本地化):
String.prototype.format = function(tokens) { var formatted = this; for (var token in tokens) if (tokens.hasOwnProperty(token)) formatted = formatted.replace(RegExp("{" + token + "}", "g"), tokens[token]); return formatted; };变化将是:
var formatted = l(this);首先调用l()本地化函数.
23> Pooria..:您可以在http://www.webtoolkit.info/javascript-sprintf.html找到JavaScript的"sprintf" .
24> A T..:对于那些喜欢Node.JS及其
util.format
功能的人,我只是把它解压缩到它的vanilla JavaScript表单中(只有util.format使用的函数):exports = {}; function isString(arg) { return typeof arg === 'string'; } function isNull(arg) { return arg === null; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isBoolean(arg) { return typeof arg === 'boolean'; } function isUndefined(arg) { return arg === void 0; } function stylizeNoColor(str, styleType) { return str; } function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][3] + 'm'; } else { return str; } } function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isSymbol(arg) { return typeof arg === 'symbol'; } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) { // Format -0 as '-0'. Strict equality won't distinguish 0 from -0, // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 . if (value === 0 && 1 / value < 0) return ctx.stylize('-0', 'number'); return ctx.stylize('' + value, 'number'); } if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); // es6 symbol primitive if (isSymbol(value)) return ctx.stylize(value.toString(), 'symbol'); } function arrayToHash(array) { var hash = {}; array.forEach(function (val, idx) { hash[val] = true; }); return hash; } function objectToString(o) { return Object.prototype.toString.call(o); } function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatPrimitiveNoColor(ctx, value) { var stylize = ctx.stylize; ctx.stylize = stylizeNoColor; var str = formatPrimitive(ctx, value); ctx.stylize = stylize; return str; } function isArray(ar) { return Array.isArray(ar); } function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || {value: value[key]}; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function (line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function (line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'") .replace(/\\\\/g, '\\'); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function (key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function reduceToSingleString(output, base, braces) { var length = output.reduce(function (prev, cur) { return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // This could be a boxed primitive (new String(), etc.), check valueOf() // NOTE: Avoid calling `valueOf` on `Date` instance because it will return // a number which, when object has some additional user-stored `keys`, // will be printed out. var formatted; var raw = value; try { // the .valueOf() call can fail for a multitude of reasons if (!isDate(value)) raw = value.valueOf(); } catch (e) { // ignore... } if (isString(raw)) { // for boxed Strings, we have to remove the 0-n indexed entries, // since they just noisey up the output and are redundant keys = keys.filter(function (key) { return !(key >= 0 && key < raw.length); }); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } // now check the `raw` value to handle boxed primitives if (isString(raw)) { formatted = formatPrimitiveNoColor(ctx, raw); return ctx.stylize('[String: ' + formatted + ']', 'string'); } if (isNumber(raw)) { formatted = formatPrimitiveNoColor(ctx, raw); return ctx.stylize('[Number: ' + formatted + ']', 'number'); } if (isBoolean(raw)) { formatted = formatPrimitiveNoColor(ctx, raw); return ctx.stylize('[Boolean: ' + formatted + ']', 'boolean'); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } // Make boxed primitive Strings look like such if (isString(raw)) { formatted = formatPrimitiveNoColor(ctx, raw); base = ' ' + '[String: ' + formatted + ']'; } // Make boxed primitive Numbers look like such if (isNumber(raw)) { formatted = formatPrimitiveNoColor(ctx, raw); base = ' ' + '[Number: ' + formatted + ']'; } // Make boxed primitive Booleans look like such if (isBoolean(raw)) { formatted = formatPrimitiveNoColor(ctx, raw); base = ' ' + '[Boolean: ' + formatted + ']'; } if (keys.length === 0 && (!array || value.length === 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function (key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold': [1, 22], 'italic': [3, 23], 'underline': [4, 24], 'inverse': [7, 27], 'white': [37, 39], 'grey': [90, 39], 'black': [30, 39], 'blue': [34, 39], 'cyan': [36, 39], 'green': [32, 39], 'magenta': [35, 39], 'red': [31, 39], 'yellow': [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'symbol': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; var formatRegExp = /%[sdj%]/g; exports.format = function (f) { if (!isString(f)) { var objects = []; for (var j = 0; j < arguments.length; j++) { objects.push(inspect(arguments[j])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function (x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; };收获自:https://github.com/joyent/node/blob/master/lib/util.js
25> 小智..:对于基本格式:
var template = jQuery.validator.format("{0} is not a valid value"); var result = template("abc");
26> Tracker1..:我在这里有一个稍长的JavaScript格式化程序...
你可以用几种方式格式化:
String.format(input, args0, arg1, ...)
String.format(input, obj)
"literal".format(arg0, arg1, ...)
"literal".format(obj)
此外,如果您说ObjectBase.prototype.format(例如使用DateJS),它将使用它.
例子...
var input = "numbered args ({0}-{1}-{2}-{3})"; console.log(String.format(input, "first", 2, new Date())); //Outputs "numbered args (first-2-Thu May 31 2012...Time)-{3})" console.log(input.format("first", 2, new Date())); //Outputs "numbered args(first-2-Thu May 31 2012...Time)-{3})" console.log(input.format( "object properties ({first}-{second}-{third:yyyy-MM-dd}-{fourth})" ,{ 'first':'first' ,'second':2 ,'third':new Date() //assumes Date.prototype.format method } )); //Outputs "object properties (first-2-2012-05-31-{3})"我也使用.asFormat别名并且已经有一些检测,以防已经有一个string.format(例如使用MS Ajax Toolkit(我讨厌那个库).
27> Afshin Mehra..:万一有人需要一个防止污染全局范围的函数,下面的函数也可以这样做:
function _format (str, arr) { return str.replace(/{(\d+)}/g, function (match, number) { return typeof arr[number] != 'undefined' ? arr[number] : match; }); };