我正在寻找一个与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()的一个版本,但我们不希望该框架的全部开销。
当前回答
旧答案的修改代码https://stackoverflow.com/a/18234317/19531844效率更高(没有较慢的RegExp)且更短
String.prototype.formatUnicorn = function () {
let str = this.toString();
if(!arguments.length) {
return;
};
const [args] = arguments;
for (const key of Object.keys(args)) {
str = str.replaceAll(`{${key}}`, args[key]);
};
return str;
};
用法:
"{test} {test_2} {test}".formatUnicorn({"test": "hello", "test_2": "world"}); // yields hello world hello
新旧基准:https://jsben.ch/BRovx
其他回答
我们可以为Typescript使用一个简单的轻量级String.Format字符串操作库。
String.Format():
var id = image.GetId()
String.Format("image_{0}.jpg", id)
output: "image_2db5da20-1c5d-4f1a-8fd4-b41e34c8c5b5.jpg";
说明符的字符串格式:
var value = String.Format("{0:L}", "APPLE"); //output "apple"
value = String.Format("{0:U}", "apple"); // output "APPLE"
value = String.Format("{0:d}", "2017-01-23 00:00"); //output "23.01.2017"
value = String.Format("{0:s}", "21.03.2017 22:15:01") //output "2017-03-21T22:15:01"
value = String.Format("{0:n}", 1000000);
//output "1.000.000"
value = String.Format("{0:00}", 1);
//output "01"
对象的字符串格式,包括说明符:
var fruit = new Fruit();
fruit.type = "apple";
fruit.color = "RED";
fruit.shippingDate = new Date(2018, 1, 1);
fruit.amount = 10000;
String.Format("the {type:U} is {color:L} shipped on {shippingDate:s} with an amount of {amount:n}", fruit);
// output: the APPLE is red shipped on 2018-01-01 with an amount of 10.000
我将添加我自己的发现,这些发现是我问过之后发现的:
number_format(用于千位分隔符/货币格式)sprintf(作者同上)
遗憾的是,sprintf似乎不能像.NET的字符串格式那样处理千位分隔符格式。
PHPJS项目为许多PHP函数编写了JavaScript实现。由于PHP的sprintf()函数与C的printf()函数基本相同,所以它们的JavaScript实现应该可以满足您的需求。
我需要更进一步的解决方案。
我可以重用一个模板,不仅在声明中生成字符串,而且在执行时间的随机时间生成字符串。
所以我遇到了这个夹具:
class Texplate{
constructor(...args){
this.data = args;
}
apply(...args){
var text = "";
var i = 0, j = 0, n = this.data.length, m = args.length;
for(;i < n && j < m; i++, j++){
text += this.data[i] + args[j];
}
for (; i < n; i++){
text += this.data[i];
}
for (; j < m; j++){
text += args[j];
}
return text;
}
}
这允许创建一个文本模板,该模板在内部用作数组合并算法,从构造函数中定义的文本数组开始。
使用示例:
var Textplate example = new Texplate("Hello, ", "!");
console.log(example.apply("Frank"));
console.log(example.apply("Mary"));
console.log(example.apply());
console.log(example.apply("Frank", " Have a good day!"));
如果只需要使用%s说明符格式化字符串
function _sprintf(message){
const regexp = RegExp('%s','g');
let match;
let index = 1;
while((match = regexp.exec(message)) !== null) {
let replacement = arguments[index];
if (replacement) {
let messageToArray = message.split('');
messageToArray.splice(match.index, regexp.lastIndex - match.index, replacement);
message = messageToArray.join('');
index++;
} else {
break;
}
}
return message;
}
_sprintf("my name is %s, my age is %s", "bob", 50); // my name is bob, my age is 50