JavaScript equivalent of Python's format() function?

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

    For those looking for a simple ES6 solution.

    First of all I'm providing a function instead of extending native String prototype because it is generally discouraged.

    // format function using replace() and recursion
    
    const format = (str, arr) => arr.length > 1 
    	? format(str.replace('{}', arr[0]), arr.slice(1)) 
    	: (arr[0] && str.replace('{}', arr[0])) || str
    
    // Example usage
    
    const str1 = 'The {} brown {} jumps over the {} dog'
    
    const formattedString = formatFn(str1, ['quick','fox','lazy'])
    
    console.log(formattedString)

    0 讨论(0)
  • 2020-12-13 09:12

    You can use template literals in JS,

    const bar1 = 'foobar'
    const bar2 = 'jumped'
    const bar3 = 'dog'
    foo = `The lazy ${bar3} ${bar2} over the ${bar1}`
    

    I think this was helpful.

    0 讨论(0)
  • 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));

    0 讨论(0)
  • 2020-12-13 09:13

    In the file

    https://github.com/BruceSherwood/glowscript/blob/master/lib/glow/api_misc.js

    is a function String.prototype.format = function(args) that fully implements the Python string.format() function, not limited simply to handling character strings.

    0 讨论(0)
  • 2020-12-13 09:17

    My own srtipped down version of YAHOO's printf reported by PatrikAkerstrand:

    function format() { 
      return [...arguments].reduce((acc, arg, idx) => 
        acc.replace(new RegExp("\\{" + (idx - 1) + "\\}", "g"), arg));
    }
    
    console.log(
      format('Confirm {1} want {0} beers', 3, 'you')
    );

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