'Beginning at the end of 'a', insert 'b' after every 3rd character of 'a'

I've been trying to solve this challenge (found at jschallenger.com):

  1. Write a function that takes two strings (a and b) as arguments
  2. Beginning at the end of 'a', insert 'b' after every 3rd character of 'a'
  3. Return the resulting string

This is my solution so far (Which I was sure would work):

function insertEveryThree(a, b) {
  let arr = a.split('')

  for (let i = arr.length - 3; i > 0; i -= 3) {

    arr.splice(i, 0, b)

  }
  return arr.join('')
}

console.log(insertEveryThree('actionable', '-')) // a-cti-ona-ble
console.log(insertEveryThree('1234567', '.')) // 1.234.567
console.log(insertEveryThree('abcde', '$')) // ab$cde
console.log(insertEveryThree('zxyzxyzxyzxyzxyz', 'w')) // zwxyzwxyzwxyzwxyzwxyz

Where am I failing at?



Solution 1:[1]

You could replace the string with a regular expression.

function insertEveryThree(a, b) {
    return a.replace(/(?=(...)+$)/g, b);
}

console.log(insertEveryThree('actionable', '-')) // a-cti-ona-ble
console.log(insertEveryThree('1234567', '.')) // 1.234.567
console.log(insertEveryThree('abcde', '$')) // ab$cde
console.log(insertEveryThree('zxyzxyzxyzxyzxyz', 'w')) // zwxyzwxyzwxyzwxyzwxyz

Solution 2:[2]

You need to push into a new array, splicing mutates the array and causes problems with indexes:

function insertEveryThree(str, character, index = 3) {
  const strArr = str.split("");
  const newArr = [];

  for (const i = 0; i < str.length; i++) {
    newArr.push(strArr[i]);

    if ((i + 1) % index === 0 && i !== 0 && i + 1 < str.length) {
      newArr.push(character);
    }
  }

  return newArr.join("");
}
console.log(insertEveryThree("actionable", "-")); // act-ion-abl-e
console.log(insertEveryThree("1234567", ".")); // 123.456.7
console.log(insertEveryThree("abcde", "$")); // abc$de
console.log(insertEveryThree("zxyzxyzxyzxyzxyz", "w")); // zxywzxywzxywzxywzxywz

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nina Scholz
Solution 2 Chris Bradshaw