JavaScript equivalent of Python's format() function?

前端 未结 17 2091
慢半拍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:12

    Usando split:

    String.prototype.format = function (args) {
        var text = this
        for(var attr in args){
            text = text.split('${' + attr + '}').join(args[attr]);
        }
        return text
    };
    
    json = {'who':'Gendry', 'what':'will sit', 'where':'in the Iron Throne'}
    text = 'GOT: ${who} ${what} ${where}';
    
    console.log('context: ',json);
    console.log('template: ',text);
    console.log('formated: ',text.format(json));

    Usando Regex:

    String.prototype.format = function (args) {
        var text = this
        for(var attr in args){
            var rgx = new RegExp('${' + attr + '}','g');
            text = text.replace(rgx, args[attr]);
        }
        return text
    };
    
    json = {'who':'Gendry', 'what':'will sit', 'where':'in the Iron Throne'}
    text = 'GOT: ${who} ${what} ${where}';
    
    console.log('context: ',json);
    console.log('template: ',text);
    console.log('formated: ',text.format(json));

提交回复
热议问题