Python的格式()函数的JavaScript等价物? [英] JavaScript equivalent of Python's format() function?
本文介绍了Python的格式()函数的JavaScript等价物?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
pre $ bar $ ='foobar'
bar2 ='jumped'
bar3 ='dog'
foo ='懒惰的'+ bar3 +''+ bar2'在'+ bar1
#懒惰的狗跳过foobar
到这里:
bar1 ='foobar'
bar2 ='jumped'
bar3 ='dog'
foo ='懒惰{} {} {}格式(bar3,bar2,bar1)
#懒狗跳过foobar
JavaScript有这样的功能?如果没有,我将如何创建一个遵循与Python的实现相同的语法?
解决方案
另一种方法,使用 String.prototype.replace
方法,以replacer函数作为第二个参数:
String.prototype.format = function(){
var i = 0,args = arguments;
return this.replace(/ {} / g,function(){
返回typeof args [i]!='undefined'?args [i ++]:'';
});
};
var bar1 ='foobar',
bar2 ='jumped',
bar3 ='dog';
$ b $ {} {}格式(bar3,bar2,bar1)上的延迟{} {}
//懒狗跳过foobar
Python has this beautiful function to turn this:
bar1 = 'foobar'
bar2 = 'jumped'
bar3 = 'dog'
foo = 'The lazy ' + bar3 + ' ' + bar2 ' over the ' + bar1
# The lazy dog jumped over the foobar
Into this:
bar1 = 'foobar'
bar2 = 'jumped'
bar3 = 'dog'
foo = 'The lazy {} {} over the {}'.format(bar3, bar2, bar1)
# The lazy dog jumped over the foobar
Does JavaScript have such a function? If not, how would I create one which follows the same syntax as Python's implementation?
解决方案
Another approach, using the String.prototype.replace
method, with a "replacer" function as second argument:
String.prototype.format = function () {
var i = 0, args = arguments;
return this.replace(/{}/g, function () {
return typeof args[i] != 'undefined' ? args[i++] : '';
});
};
var bar1 = 'foobar',
bar2 = 'jumped',
bar3 = 'dog';
'The lazy {} {} over the {}'.format(bar3, bar2, bar1);
// "The lazy dog jumped over the foobar"
这篇关于Python的格式()函数的JavaScript等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文