2011-04-09 100 views
3

有没有更好的方法来做到这一点?我在这里使用下划线js lib,这是_的地方。来自。我习惯于这种程序来格式化Python中的字符串,并且我喜欢简单的JavaScript,而不必一直执行+ + +。这有效,但感觉就像我重新发明了轮子。在javascript中格式化python字符串


function foo (iterable, string) { 
    var s = iterable.shift(); 
    string = string.replace("%s",s); 
    return _.isEmpty(iterable) ? string : foo(iterable,string); 
}; 

foo(['sam','green','ham'],"%s likes %s eggs and %s."); 
"sam likes green eggs and ham." 
+0

感谢您的意见。这两个看起来都很酷,我必须检查出来。 – 2011-04-10 04:14:35

回答

1

尝试使用sprintf lib,特别是vsprintf。

vsprintf('The first 4 letters of the english alphabet are: %s, %s, %s and %s', ['a', 'b', 'c', 'd']);