ℙℕℤℝ 2009-03-04 12:53
浏览 596
已采纳

等价于 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条回答 默认 最新

  • MAO-EYE 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 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的