Reputation: 55
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"
Upvotes: 2
Views: 124
Reputation: 7866
Here's a concise solution :)
const result = 'abcd'.replace(/./g, (c, i) => c.repeat(i+1));
document.write(result);
Note: arrow functions, const
and repeat
come with ES6.
Upvotes: 1
Reputation: 386654
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);
Upvotes: 1
Reputation: 21672
While it would've been nice to see your attempts, try this out:
function addString(str) {
var output = "";
str.split("").forEach(function(i, k) { //Split string up, loop through chars
output += Array(k+2).join(str[k]);
});
return output;
}
var myText = prompt("Enter a word.");
alert(addString(myText));
You can create n
occurrences of c
using the method...
function repeatChar(n, c){
return Array(n+1).join(c);
}
I've manipulated this logic to fit your question, in particular incrementing the array length by 2 instead of 1, so that index 0 is printed 1 time, and so-on.
Upvotes: 1