javascript中的python字符串格式

时间:2011-04-09 16:55:09

标签: javascript python underscore.js

有更好的方法吗?我在这里使用下划线js lib,这是_的地方。来自。我已经习惯了这种在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 个答案:

答案 0 :(得分:1)

试用sprintf lib,特别是vsprintf。

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