Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!