Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

164
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda