JavaScript equivalent of Python's format() function?

前端 未结 17 2127
慢半拍i
慢半拍i 2020-12-13 08:42

Python has this beautiful function to turn this:

bar1 = \'foobar\'
bar2 = \'jumped\'
bar3 = \'dog\'

foo = \'The lazy \' + bar3 + \' \' + bar2 \' over the \'         


        
17条回答
  •  不知归路
    2020-12-13 09:10

    JS:

    String.prototype.format = function () {
        var str = this;
        for (var i = 0; i < arguments.length; i++) {
            str = str.replace('{' + i + '}', arguments[i]);
        }
        return str;
    }
    
    bar1 = 'foobar';
    bar2 = 'jumped';
    bar3 = 'dog';
    
    python_format = 'The lazy {2} {1} over the {0}'.format(bar1,bar2,bar3);
    
    document.getElementById("demo").innerHTML = "JavaScript equivalent of Python's format() function:
    " + python_format + "";

    HTML:

    CSS:

    span#python_str {
        color: red;
        font-style: italic;
    }
    

    OUTPUT:

    JavaScript equivalent of Python's format() function:

    The lazy dog jumped over the foobar

    DEMO:

    jsFiddle

提交回复
热议问题