如何用数组的值替换字符串中的问号?
给定字符串 'Hello ?,welcome to ?'
和数组 ['foo', 'bar']
,如何获取字符串 'Hello foo ,欢迎使用 JavaScript(可能使用 jQuery、Underscore 等)在一行代码中使用 bar'
?
Given the string 'Hello ?, welcome to ?'
and the array ['foo', 'bar']
, how do I get the string 'Hello foo, welcome to bar'
in a single line of code with JavaScript (possibly with jQuery, Underscore, etc.)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
将所有内容都放在一行中有点愚蠢,但是:
Kind of silly to put it all on one line, but:
您可以使用 vsprintf。尽管如果包含 sprintf,它就不止一行了。
You could use vsprintf. Although if you include sprintf, it's much more than one line.
让我们构建一个
replaceWith
函数:它是一个柯里化函数:它接受替换字符串列表并返回另一个函数,该函数将逐个返回替换内容:
Let's build a
replaceWith
function:It's a curried function: it takes a list of replacement strings and returns another function which will return the replacements one by one:
After the third call you have exhausted all the replacements so the next calls will either return
undefined
or whatever you passed as afallback
parameter:This
fallback
parameter can be handy if you have more substrings to replace than replacement strings at your disposal. (But we will come to that later.)Now using
replaceWith
we can do:Behind the scene it calls the function returned by
replaceWith
(let's call itfn
) with:The
fallback
parameter (i.e. your placeholder'?'
in this case) is ignored while there are still replacement strings. However it will be returned as is when there are more placeholders than replacements:Acknowledgment
This answer is a variation of Alex Varghese excellent answer.