我正在寻找一个与C/PHP printf()或C#/Java程序员String.Format()(IFormatProvider for.NET)相当的JavaScript。
目前,我的基本要求是数字的千位分隔符格式,但处理大量组合(包括日期)的格式会很好。
我意识到Microsoft的Ajax库提供了String.Format()的一个版本,但我们不希望该框架的全部开销。
我正在寻找一个与C/PHP printf()或C#/Java程序员String.Format()(IFormatProvider for.NET)相当的JavaScript。
目前,我的基本要求是数字的千位分隔符格式,但处理大量组合(包括日期)的格式会很好。
我意识到Microsoft的Ajax库提供了String.Format()的一个版本,但我们不希望该框架的全部开销。
当前回答
使用Lodash,您可以获得模板功能:
使用ES模板文本分隔符作为“插入”分隔符。通过替换“interpole”分隔符禁用支持。
var compiled = _.template('hello ${ user }!');
compiled({ 'user': 'pebbles' });
// => 'hello pebbles!
其他回答
当前JavaScript
从上的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}}。所以要像恐惧噬菌体的建议那样同时进行替换。
JavaScript有“sprintf”,您可以在http://www.webtoolkit.info/javascript-sprintf.html.
这里是sprintf在JavaScript中的一个最小实现:它只执行“%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
与之前回复中的类似解决方案相比,此解决方案一次性完成所有替换,因此不会替换先前替换值的部分。
现在,有一个名为locatus的包,它将其他语言的函数转换为Javascript,如php、python、ruby等。
const printf = require('locutus/php/strings/printf')
printf('Hello world');
你可以试试这个游乐场代码沙盒
这很有趣,因为Stack Overflow实际上有自己的格式化函数,用于名为formatUnicorn的String原型。试试看!进入控制台并键入以下内容:
"Hello, {name}, are you feeling {adjective}?".formatUnicorn({name:"Gabriel", adjective: "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样式的对象,那么你几乎可以得到C#的String.Format行为。
"a{0}bcd{1}ef".formatUnicorn("FOO", "BAR"); // yields "aFOObcdBARef"
这是因为Array的切片会将参数中的任何内容强制到Array中,无论它最初是不是这样,并且关键字将是每个数组元素的索引(0,1,2…),该索引被强制到字符串中(例如,“0”,因此第一个正则表达式模式为“\\{0\\}”)。
整洁的