Skip to content
Advertisement

How do I write a JavaScript program for the question given below

Write a function that takes three (str, c, n) arguments. Start with the end of ‘str’. Insert character c after every n characters?

function three(str, c, n){
  for(let i =0; i<str.length; i= i+n){
   str.slice(i, i+n);
   str = str + c;
  }
  return str;
}
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:

function three (str, c, n) {
  return str.split('').reverse().map((currentValue, currentIndex, array) => {
    if (currentIndex % n === 0) {
      return currentValue + c
    } else {
      return currentValue
    }
  }).reverse().join('')
}

console.log(three("apple", "c", 2));
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement