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

130
Views
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 answers
Answer question

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 Report

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 Report

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 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!