JavaScript equivalent of Python's format() function?

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

提交回复
热议问题