Use of String.Format in JavaScript?

后端 未结 19 2079
逝去的感伤
逝去的感伤 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:44

    Here is what I use. I have this function defined in a utility file:

      String.format = function() {
          var s = arguments[0];
          for (var i = 0; i < arguments.length - 1; i++) {       
              var reg = new RegExp("\\{" + i + "\\}", "gm");             
              s = s.replace(reg, arguments[i + 1]);
          }
          return s;
      }
    

    And I call it like so:

    var greeting = String.format("Hi, {0}", name);
    

    I do not recall where I found this, but it has been very useful to me. I like it because the syntax is the same as the C# version.

提交回复
热议问题