Use of String.Format in JavaScript?

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

    Here is an solution that allows both prototype and function options.

    // --------------------------------------------------------------------
    // Add prototype for 'String.format' which is c# equivalent
    //
    // String.format("{0} i{2}a night{1}", "This", "mare", "s ");
    // "{0} i{2}a night{1}".format("This", "mare", "s ");
    // --------------------------------------------------------------------
    
    if(!String.format)
        String.format = function(){
            for (var i = 0, args = arguments; i < args.length - 1; i++)
                args[0] = args[0].replace("{" + i + "}", args[i + 1]);
            return args[0];
        };
    if(!String.prototype.format && String.format)
        String.prototype.format = function(){
            var args = Array.prototype.slice.call(arguments).reverse();
            args.push(this);
            return String.format.apply(this, args.reverse())
        };
    

    Enjoy.

提交回复
热议问题