本文介绍了JavaScript 等价于 printf/String.Format的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找与 C/PHP printf() 或 C#/Java 程序员等效的良好 JavaScript,String.Format() (IFormatProvider for .NET).

I'm looking for a good JavaScript equivalent of the C/PHP printf() or for C#/Java programmers, String.Format() (IFormatProvider for .NET).

我现在的基本要求是数字的千位分隔符格式,但处理大量组合(包括日期)的东西会很好.

My basic requirement is a thousand separator format for numbers for now, but something that handles lots of combinations (including dates) would be good.

我意识到 Microsoft 的 Ajax 库提供了一个 String 版本.Format(),但我们不想要该框架的全部开销.

I realize Microsoft's Ajax library provides a version of String.Format(), but we don't want the entire overhead of that framework.

推荐答案

Current JavaScript

从 ES6 开始,您可以使用模板字符串:

Current JavaScript

From ES6 on you could use template strings:

let soMany = 10;
console.log(`This is ${soMany} times easier!`);
// "This is 10 times easier!

有关详细信息,请参阅下方 Kim 的答案.

See Kim's answer below for details.

尝试 sprintf() for JavaScript.

如果你真的想自己做一个简单的格式化方法,不要连续进行替换,而是同时进行.

If you really want to do a simple format method on your own, don’t do the replacements successively but do them simultaneously.

因为当先前替换的替换字符串也包含这样的格式序列时,提到的大多数其他提议都失败了:

Because most of the other proposals that are mentioned fail when a replace string of previous replacement does also contain a format sequence like this:

"{0}{1}".format("{1}", "{0}")

通常您希望输出为 {1}{0},但实际输出为 {1}{1}.因此,请同时进行替换,例如 fearphage 的建议.

Normally you would expect the output to be {1}{0} but the actual output is {1}{1}. So do a simultaneously replacement instead like in fearphage’s suggestion.

这篇关于JavaScript 等价于 printf/String.Format的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 09:25