如何用数组的值替换字符串中的问号?

Mau*_*ras 5 javascript string jquery underscore.js

给定字符串'Hello ?, welcome to ?'和数组['foo', 'bar'],如何'Hello foo, welcome to bar'使用JavaScript(可能使用jQuery,Underscore等)在单行代码中获取字符串?

Sam*_*lgh 22

var s = 'Hello ?, welcome to ?';
var a = ['foo', 'bar'];
var i = 0;
alert(s.replace(/\?/g,function(){return a[i++]}));
Run Code Online (Sandbox Code Playgroud)

  • +1你也可以通过使用`return a.shift()`消除`i`(尽管`a`之后会是空的). (2认同)

And*_*ker 7

把它全部放在一条线上有点傻,但是:

var str = 'Hello ?, welcome to ?',
    arr = ['foo', 'bar'],
    i = 0;


while(str.indexOf("?") >= 0) { str = str.replace("?", arr[i++]); }
Run Code Online (Sandbox Code Playgroud)