Use of String.Format in JavaScript?

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

    String.Format method from .NET Framework has multiple signatures. The one I like the most uses params keyword in its prototype, i.e.:

    public static string Format(
        string format,
        params Object[] args
    )
    

    Using this version, you can not only pass variable number of arguments to it but also an array argument.

    Because I like the straightforward solution provided by Jeremy, I'd like to extend it a bit:

    var StringHelpers = {
        format: function(format, args) {
            var i;
            if (args instanceof Array) {
                for (i = 0; i < args.length; i++) {
                    format = format.replace(new RegExp('\\{' + i + '\\}', 'gm'), args[i]);
                }
                return format;
            }
            for (i = 0; i < arguments.length - 1; i++) {
                format = format.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i + 1]);
            }
            return format;
        }
    };
    

    Now you can use your JavaScript version of String.Format in the following manners:

    StringHelpers.format("{0}{1}", "a", "b")
    

    and

    StringHelpers.format("{0}{1}", ["a", "b"])
    

提交回复
热议问题