Use of String.Format in JavaScript?

后端 未结 19 1919
逝去的感伤
逝去的感伤 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 09:01
    //Add "format" method to the string class
    //supports:  "Welcome {0}. You are the first person named {0}".format("David");
    //       and "First Name:{} Last name:{}".format("David","Wazy");
    //       and "Value:{} size:{0} shape:{1} weight:{}".format(value, size, shape, weight)
    String.prototype.format = function () {
        var content = this;
        for (var i = 0; i < arguments.length; i++) {
            var target = '{' + i + '}';
            content=content.split(target).join(String(arguments[i]))
            content = content.replace("{}", String(arguments[i]));
        }
        return content;
    }
    alert("I {} this is what {2} want and {} works for {2}!".format("hope","it","you"))
    

    You can mix and match using positional and "named" replacement locations using this function.

    0 讨论(0)
提交回复
热议问题