在JavaScript中进行Python字符串格式化
有没有更好的方法来做到这一点?我在这里使用的是underscore.js这个库,所以前面有个_.的标记。我习惯用Python来格式化字符串,想在JavaScript中找到一个简单的方法,不想一直用加号拼接字符串。这种方法可以用,但我觉得好像是在重复发明轮子。
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."
1 个回答
1
可以试试这个叫做 sprintf 的库,特别是里面的 vsprintf 功能。
vsprintf('The first 4 letters of the english alphabet are: %s, %s, %s and %s', ['a', 'b', 'c', 'd']);