How to replace question marks inside a string with the values of an array?

前端 未结 5 1174
别那么骄傲
别那么骄傲 2020-12-03 19:11

Given the string \'Hello ?, welcome to ?\' and the array [\'foo\', \'bar\'], how do I get the string \'Hello foo, welcome to bar\' in

相关标签:
5条回答
  • 2020-12-03 19:22
    var s = 'Hello ?, welcome to ?';
    var a = ['foo', 'bar'];
    var i = 0;
    alert(s.replace(/\?/g,function(){return a[i++]}));
    
    0 讨论(0)
  • 2020-12-03 19:40

    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('                                                                    
    0 讨论(0)
  • 2020-12-03 19:46

    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++]); }
    
    0 讨论(0)
  • 2020-12-03 19:46

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

    0 讨论(0)
  • 2020-12-03 19:47

    You could use vsprintf. Although if you include sprintf, it's much more than one line.

    vsprintf('Hello %s, welcome to %s', [foo, bar]);
    
    0 讨论(0)
提交回复
热议问题