开发者

python string formatting in javascript

开发者 https://www.devze.com 2023-02-23 00:57 出处:网络
Is there a better way to do this?I\'m using the underscore js lib here, which is where the _. comes from.I\'m used to this sort of procedure to format strings in python and i\'d like something simple

Is there a better way to do this? I'm using the underscore js lib here, which is where the _. comes from. I'm used to this sort of procedure to format strings in python and i'd like something simple for javascript without doing + + + + all the time. This works, but it feels like i reinvented the wheel.


function foo (iterable, string) {
  var s = iterable.shift();
  string = string.replace("%s",s);
  return _.isEmpty(iterable) ? string : foo(iterable,st开发者_开发问答ring);
};

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


try out the sprintf lib, specifically vsprintf.

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

精彩评论

暂无评论...
验证码 换一张
取 消