skip to Main Content

say a I have a var like

var str = 'the @ brown @ fox @ jumped @ over @ the @ fence'

can I replace it with

var str = 'the 1 brown 2 fox 3 jumped 4 over 5 the 6 fence'

maybe array.from can help

4

Answers


  1. Chosen as BEST ANSWER
    'the @ brown @ fox @ jumped @ over @ the @ fence'
    .split('@')
    .reduce((acc,cur,i,s)=> `${acc+cur}${(i+1)!==s.length?`$${i+1}`:''}`,'')
    

  2. You can use String#replace with a callback that keeps track of the count.

    let str = 'the @ brown @ fox @ jumped @ over @ the @ fence';
    let i = 0, res = str.replace(/@/g, () => ++i);
    console.log(res);

    Or, similarly with String#replaceAll:

    let str = 'the @ brown @ fox @ jumped @ over @ the @ fence';
    let i = 0, res = str.replaceAll('@', () => ++i);
    console.log(res);
    Login or Signup to reply.
  3. Regex approach:

    using replace with i which is gonna be incremented each time find character @:

    let str = 'the @ brown @ fox @ jumped @ over @ the @ fence';
    let i=0;
    console.log(str.replace(/@/g, _ => ++i))

    for-loop approach

    let str = 'the @ brown @ fox @ jumped @ over @ the @ fence';
    let arr = str.split('@');//[ "the ", " brown ", " fox ", " jumped ", " over ", " the ", " fence" ]
    let result = arr[0];
    for (let i = 1; i < arr.length; i++) {
      result += i + arr[i];
    }
    console.log(result)

    reduce approach:

    let str = 'the @ brown @ fox @ jumped @ over @ the @ fence';
    let arr = str.split('@');
    console.log(arr
      .reduce((acc, curr, i) =>
        acc + (i !== 0 ? i : '') + curr, ''))
    Login or Signup to reply.
  4. You could take a closure with a start value of one for the index.

    const
        str = 'the @ brown @ fox @ jumped @ over @ the @ fence',
        result = str.replace(/@/g, (i => _ => i++)(1));
    
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search