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.)?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
var s = 'Hello ?, welcome to ?';
var a = ['foo', 'bar'];
var i = 0;
alert(s.replace(/\?/g,function(){return a[i++]}));
回答2:
Kind of silly to put it all on one line, but:
var str = 'Hello ?, welcome to ?',
arr = ['foo', 'bar'],
i = 0;
while(str.indexOf("?") >= 0) { str = str.replace("?", arr[i++]); }
回答3:
You could use vsprintf. Although if you include sprintf, it's much more than one line.
vsprintf('Hello %s, welcome to %s', [foo, bar]);
回答4:
let str = 'Hello ?, welcome to ?'
let arr = ['foo', 'bar']
const fn = Array.prototype.shift.bind(arr)
let result = str.replace(/\?/g, fn)
console.log(result);