Use of String.Format in JavaScript?

后端 未结 19 2075
逝去的感伤
逝去的感伤 2020-12-04 07:59

This is driving me nuts. I believe I asked this exact same question, but I can\'t find it any more (I used Stack Overflow search, Google Search, manually searched my po

19条回答
  •  悲&欢浪女
    2020-12-04 08:51

    Here is a useful string formatting function using regular expressions and captures:

    function format (fmtstr) {
      var args = Array.prototype.slice.call(arguments, 1);
      return fmtstr.replace(/\{(\d+)\}/g, function (match, index) {
        return args[index];
      });
    }
    

    Strings can be formatted like C# String.Format:

    var str = format('{0}, {1}!', 'Hello', 'world');
    console.log(str); // prints "Hello, world!"
    

    the format will place the correct variable in the correct spot, even if they appear out of order:

    var str = format('{1}, {0}!', 'Hello', 'world');
    console.log(str); // prints "world, Hello!"
    

    Hope this helps!

提交回复
热议问题