JavaScript equivalent to printf/String.Format

前端 未结 30 2500
囚心锁ツ
囚心锁ツ 2020-11-21 04:27

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

30条回答
  •  既然无缘
    2020-11-21 05:01

    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.


    Otherwise:

    Try 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}")
    

    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.

提交回复
热议问题