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

129
Visualizações
Generate list of numbers with a character in between every nth numbers

I am trying to generate a string with the numbers from 1 to 1000 with the character '*' after every 5th numbers e.g.,

1 2 3 4 5 * 6 7 8 9 10 * 11 12 13 14 15 * 16 17 18 19 20 * …

Here's my attempt but as you can it is not working as expected:

const insertCharacter = () => {
    let contain = [];
    let new_value;
    for (let i = 1; i <= 1000; i++) {
         contain += [i];
         if (contain.length)
         contain.toString()
         let parts = contain.match(/.{0,5}/g);
         new_value = parts.join("*");
    }
    return new_value;
}
console.log(insertCharacter());

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

I would suggest using the modulus here:

var output = "";
for (var i=1; i <= 1000; ++i) {
    if (i > 1 && i % 5 == 1) output += " *";
    if (i > 1) output += " ";
    output += i;
}
console.log(output);

about 4 years ago · Juan Pablo Isaza Relatório

0

Older JavaScript format version, but still valid.

The % is called a Remainder and is the key here.

Sample code is only counting to 50.

Edit: Changed to commented version from mplungjan.

Edit 2, for comment from georg. If you do not want a trailing Asterisk, some options:

  • count to 999, then add 1000 to the result
  • use result.substring(0,result.length-2)

var i, result = "";
for(i=1;i<51;i++){
  result += i + (i % 5 ? " " : " * ");
}
console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

Please refer this code.

const result = [...Array(1000)].map((val, index) => (index + 1) % 5 === 0 ? index + 1 + " *" : index + 1);
console.log(result.join(' '));

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