JavaScript equivalent to printf/String.Format

前端 未结 30 2431
囚心锁ツ
囚心锁ツ 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条回答
  •  闹比i
    闹比i (楼主)
    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).

提交回复
热议问题