Use of String.Format in JavaScript?

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

    Aside from the fact that you are modifying the String prototype, there is nothing wrong with the function you provided. The way you would use it is this way:

    "Hello {0},".format(["Bob"]);
    

    If you wanted it as a stand-alone function, you could alter it slightly to this:

    function format(string, object) {
        return string.replace(/{([^{}]*)}/g,
           function(match, group_match)
           {
               var data = object[group_match];
               return typeof data === 'string' ? data : match;
           }
        );
    }
    

    Vittore's method is also good; his function is called with each additional formating option being passed in as an argument, while yours expects an object.

    What this actually looks like is John Resig's micro-templating engine.

提交回复
热议问题