Search code examples
javascriptsplice

Splicing a string and adding the same value for the index of the place of that value?


I think I am pretty close to figuring this one out but was getting stumped.

I am trying to splice any string taken by a function and returning that string a value added for the place it holds in the string.

function addString();

When this function recieves a value like this:

let message = "abcd";

It will return that value like this:

console.log(addString(message));
"abbcccdddd"

Solution

  • You could map the repeated value and join to a single string.

    let message = "abcd",
        result = [...message].map((c, i) => c.repeat(i + 1)).join('');
    
    console.log(result);