JavaScript equivalent of Python's format() function?

前端 未结 17 2116
慢半拍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 08:55

    Here's my first attempt. Feel free to point out flaws.

    Example: http://jsfiddle.net/wFb2p/5/

    String.prototype.format = function() {
        var str = this;
        var i = 0;
        var len = arguments.length;
        var matches = str.match(/{}/g);
        if( !matches || matches.length !== len ) {
            throw "wrong number of arguments";
        }
        while( i < len ) {
            str = str.replace(/{}/, arguments[i] );
            i++;
        }
        return str;
    };
    

    EDIT: Made it a bit more efficient by eliminating the .match() call in the while statement.

    EDIT: Changed it so that the same error is thrown if you don't pass any arguments.

提交回复
热议问题