How to replace question marks inside a string with

2020-03-03 08:38发布

问题:

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);