JavaScript equivalent to printf/String.Format

前端 未结 30 2494
囚心锁ツ
囚心锁ツ 2020-11-21 04:27

I\'m looking for a good JavaScript equivalent of the C/PHP printf() or for C#/Java programmers, String.Format() (IFormatProvider for .

相关标签:
30条回答
  • 2020-11-21 05:16

    Very elegant:

    String.prototype.format = function (){
        var args = arguments;
        return this.replace(/\{\{|\}\}|\{(\d+)\}/g, function (curlyBrack, index) {
            return ((curlyBrack == "{{") ? "{" : ((curlyBrack == "}}") ? "}" : args[index]));
        });
    };
    
    // Usage:
    "{0}{1}".format("{1}", "{0}")
    

    Credit goes to (broken link) https://gist.github.com/0i0/1519811

    0 讨论(0)
  • 2020-11-21 05:17

    One very slightly different version, the one I prefer (this one uses {xxx} tokens rather than {0} numbered arguments, this is much more self-documenting and suits localization much better):

    String.prototype.format = function(tokens) {
      var formatted = this;
      for (var token in tokens)
        if (tokens.hasOwnProperty(token))
          formatted = formatted.replace(RegExp("{" + token + "}", "g"), tokens[token]);
      return formatted;
    };
    

    A variation would be:

      var formatted = l(this);
    

    that calls an l() localization function first.

    0 讨论(0)
  • 2020-11-21 05:17

    I have a slightly longer formatter for JavaScript here...

    You can do formatting several ways:

    • String.format(input, args0, arg1, ...)
    • String.format(input, obj)
    • "literal".format(arg0, arg1, ...)
    • "literal".format(obj)

    Also, if you have say a ObjectBase.prototype.format (such as with DateJS) it will use that.

    Examples...

    var input = "numbered args ({0}-{1}-{2}-{3})";
    console.log(String.format(input, "first", 2, new Date()));
    //Outputs "numbered args (first-2-Thu May 31 2012...Time)-{3})"
    
    console.log(input.format("first", 2, new Date()));
    //Outputs "numbered args(first-2-Thu May 31 2012...Time)-{3})"
    
    console.log(input.format(
        "object properties ({first}-{second}-{third:yyyy-MM-dd}-{fourth})"
        ,{
            'first':'first'
            ,'second':2
            ,'third':new Date() //assumes Date.prototype.format method
        }
    ));
    //Outputs "object properties (first-2-2012-05-31-{3})"
    

    I've also aliased with .asFormat and have some detection in place in case there's already a string.format (such as with MS Ajax Toolkit (I hate that library).

    0 讨论(0)
  • 2020-11-21 05:20

    It's funny because Stack Overflow actually has their own formatting function for the String prototype called formatUnicorn. Try it! Go into the console and type something like:

    "Hello, {name}, are you feeling {adjective}?".formatUnicorn({name:"Gabriel", adjective: "OK"});
    

    Firebug

    You get this output:

    Hello, Gabriel, are you feeling OK?

    You can use objects, arrays, and strings as arguments! I got its code and reworked it to produce a new version of String.prototype.format:

    String.prototype.formatUnicorn = String.prototype.formatUnicorn ||
    function () {
        "use strict";
        var str = this.toString();
        if (arguments.length) {
            var t = typeof arguments[0];
            var key;
            var args = ("string" === t || "number" === t) ?
                Array.prototype.slice.call(arguments)
                : arguments[0];
    
            for (key in args) {
                str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
            }
        }
    
        return str;
    };
    

    Note the clever Array.prototype.slice.call(arguments) call -- that means if you throw in arguments that are strings or numbers, not a single JSON-style object, you get C#'s String.Format behavior almost exactly.

    "a{0}bcd{1}ef".formatUnicorn("foo", "bar"); // yields "aFOObcdBARef"
    

    That's because Array's slice will force whatever's in arguments into an Array, whether it was originally or not, and the key will be the index (0, 1, 2...) of each array element coerced into a string (eg, "0", so "\\{0\\}" for your first regexp pattern).

    Neat.

    0 讨论(0)
  • 2020-11-21 05:20

    I use a small library called String.format for JavaScript which supports most of the format string capabilities (including format of numbers and dates), and uses the .NET syntax. The script itself is smaller than 4 kB, so it doesn't create much of overhead.

    0 讨论(0)
  • 2020-11-21 05:20

    If you are looking to handle the thousands separator, you should really use toLocaleString() from the JavaScript Number class since it will format the string for the user's region.

    The JavaScript Date class can format localized dates and times.

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