Use of String.Format in JavaScript?

后端 未结 19 1917
逝去的感伤
逝去的感伤 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.

    0 讨论(0)
  • 2020-12-04 08:54

    Without a third party function:

    string format = "Hi {0}".replace('{0}', name)
    

    With multiple params:

    string format = "Hi {0} {1}".replace('{0}', name).replace('{1}', lastname)
    
    0 讨论(0)
  • 2020-12-04 08:54

    Use sprintf library

    Here you have a link where you can find the features of this library.

    0 讨论(0)
  • 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"])
    
    0 讨论(0)
  • 2020-12-04 08:58

    Your function already takes a JSON object as a parameter:

    string format = "Hi {foo}".replace({
        "foo": "bar",
        "fizz": "buzz"
    });
    

    if you notice, the code:

    var r = o[b];
    

    looks at your parameter (o) and uses a key-value-pairs within it to resolve the "replace"

    0 讨论(0)
  • 2020-12-04 08:58
    String.prototype.format = function () {
        var formatted = this;
        for (var arg in arguments) {
            formatted = formatted.split('{' + arg + '}').join(arguments[arg]);
        }
        return formatted;
    };
    

    USAGE:

    'Hello {0}!'.format('Word')                 ->     Hello World!

    'He{0}{0}o World!'.format('l')            ->     Hello World!

    '{0} {1}!'.format('Hello', 'Word')     ->     Hello World!

    '{0}!'.format('Hello {1}', 'Word')     ->     Hello World!

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