Write a function that takes three (str, c, n) arguments. Start with the end of ‘str’. Insert character c after every n characters?
JavaScript
x
8
1
function three(str, c, n){
2
for(let i =0; i<str.length; i= i+n){
3
str.slice(i, i+n);
4
str = str + c;
5
}
6
return str;
7
}
8
console.log(three("apple", "c", 2));
I think, I am using wrong method.
Advertisement
Answer
Start with the end of ‘str’. Insert character c after every n characters?
I assumed this means the string needs to end with c
after the change. Correct me if I’m wrong.
If that’s the case Array.prototype.reverse() and Array.prototype.map() can help here:
JavaScript
1
11
11
1
function three (str, c, n) {
2
return str.split('').reverse().map((currentValue, currentIndex, array) => {
3
if (currentIndex % n === 0) {
4
return currentValue + c
5
} else {
6
return currentValue
7
}
8
}).reverse().join('')
9
}
10
11
console.log(three("apple", "c", 2));