Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

167
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda