sprintf 等效于客户端 JavaScript [英] sprintf equivalent for client-side JavaScript

查看:19
本文介绍了sprintf 等效于客户端 JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 console.log 至少支持 C 中 printf 的一些基本功能,但我很想知道如何利用console.log 的实现来创建类似于 sprintf 的东西.我知道你不能简单地使用 .bind.apply 因为 console.log 实际上并不返回字符串,所以有没有解决这个问题?

I know that console.log supports at least some of the basic features of printf from C through messing around, but I was curious of a way to take advantage of console.log's implementation to create something similar to sprintf. I know you can't simply use .bind or .apply since console.log doesn't actually return the string, so is there a way around this?

如果这实际上不可能,是否还有其他一些鲜为人知的原生实现,只需几行代码即可在 JavaScript 中实现 sprintf?

If this isn't actually possible, is there some other little-known native implementation that's only a few lines of code away from achieving sprintf in JavaScript?

对于那些不知道 sprintf 究竟是什么的人,这里是来自教程点的一些文档.我正在寻找的示例用法如下:

For those who do not know what sprintf is exactly, here is some documentation from tutorialspoint. Example usage I'm looking for is below:

var string1 = sprintf("Hello, %s!", "world");
var string2 = sprintf("The answer to everything is %d.", 42);

推荐答案

保持简单

var sprintf = (str, ...argv) => !argv.length ? str : 
    sprintf(str = str.replace(sprintf.token||"$", argv.shift()), ...argv);

由于 Javascript 自动处理数据类型,因此不需要类型选项.

Since Javascript handles data types automatically, there is no need for type options.

如果需要填充,"15".padStart(5,"0") = ("00000"+15).slice(-5) = ";00015".

If you need padding, "15".padStart(5,"0") = ("00000"+15).slice(-5) = "00015".

var sprintf = (str, ...argv) => !argv.length ? str : 
    sprintf(str = str.replace(sprintf.token||"$", argv.shift()), ...argv);

alert(sprintf("Success after $ clicks ($ seconds).", 15, 4.569));
sprintf.token = "_";
alert(sprintf("Failure after _ clicks (_ seconds).", 5, 1.569));

sprintf.token = "%";
var a = "%<br>%<br>%";
var b = sprintf("% plus % is %", 0, 1, 0 + 1);
var c = sprintf("Hello, %!", "world");
var d = sprintf("The answer to everything is %.", 42);
document.write(sprintf(a,b,c,d));

这篇关于sprintf 等效于客户端 JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆