必承其重 | 欲带皇冠 2009-03-04 12:53 采纳率: 0%
浏览 367
已采纳

等价于 printf / string。 格式

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.

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

转载于:https://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format

  • 写回答

30条回答 默认 最新

  • derek5. 2013-08-01 18:14
    关注

    Edit: From ES6 on you could use template strings:

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

    See Kim's answer below for details.

    Original answer:

    Try sprintf() for JavaScript.


    Update    Ok, 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}")
    

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(29条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器