Given the string \'Hello ?, welcome to ?\'
and the array [\'foo\', \'bar\']
, how do I get the string \'Hello foo, welcome to bar\'
in
var s = 'Hello ?, welcome to ?';
var a = ['foo', 'bar'];
var i = 0;
alert(s.replace(/\?/g,function(){return a[i++]}));
Let's build a replaceWith
function:
const replaceWith =
(...str) =>
(fallback) =>
str.length === 0
? fallback
: str.shift();
It's a curried function: it takes a list of replacement strings and returns another function which will return the replacements one by one:
const replacements = replaceWith('
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++]); }
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);
You could use vsprintf. Although if you include sprintf, it's much more than one line.
vsprintf('Hello %s, welcome to %s', [foo, bar]);