我正在寻找一个与C/PHP printf()或C#/Java程序员String.Format()(IFormatProvider for.NET)相当的JavaScript。

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

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


当前回答

在typescript中,创建一个名为format.ts的文件,并导入您需要使用的任何格式。

// contents of format.ts

interface String {
  format(...args: any[]): string;
}

if (!String.prototype.format) {
  String.prototype.format = function() {
    let a = this;
    let b: any;
    // tslint:disable-next-line: forin
    for (b in arguments) {
      a = a.replace(/%[a-z]/, arguments[b]);
    }
    return a;
  };
}

要格式化字符串,请使用以下代码:

import './format';

console.log('Hello, %s!'.format('World'));

实例

String.prototype.format=函数(){设a=此;设b;for(参数中的b){a=a.replace(/%[a-z]/,自变量[b]);}返回a;};console.log(“您好,%s!”.format(“世界”));

其他回答

我需要一个函数,它可以以用户喜欢的方式格式化价格(以美分为单位),而棘手的是,格式是由用户指定的——我不希望我的用户理解类似printf的语法或regexp等。我的解决方案与Basic中使用的解决方案有些相似,因此用户只需使用数字的#位置进行标记,例如:

simple_format(1234567,"$ ###,###,###.##")
"$ 12,345.67"
simple_format(1234567,"### ### ###,## pln")
"12 345,67 pln"

我相信这很容易被用户理解,也很容易实现:

function simple_format(integer,format){
  var text = "";
  for(var i=format.length;i--;){
    if(format[i]=='#'){
      text = (integer%10) + text;
      integer=Math.floor(integer/10);
      if(integer==0){
        return format.substr(0,i).replace(/#(.*#)?/,"")+text;
      }
    }else{
      text = format[i] + text;
    }
  }
  return text;
}

这是https://stackoverflow.com/a/4673436/1258486对于CoffeeScript。

https://gist.github.com/eces/5669361

if String.prototype.format is undefined
  String.prototype.format = () ->
    _arguments = arguments
    this.replace /{(\d+)}/g, (match, number) ->
      if typeof _arguments[number] isnt 'undefined' then _arguments[number] else match

从上的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站点以查找支持的浏览器列表。

当前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中的数字格式

我来到这个问题页面,希望找到如何在JavaScript中格式化数字,而不引入另一个库。以下是我的发现:

舍入浮点数

JavaScript中sprintf(“%.2f”,num)的等价物似乎是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参考页(带有指向Precision()、toExponential()、toLocaleString()等的链接)