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());
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);
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:
999, then add 1000 to the resultresult.substring(0,result.length-2)var i, result = "";
for(i=1;i<51;i++){
result += i + (i % 5 ? " " : " * ");
}
console.log(result);
Please refer this code.
const result = [...Array(1000)].map((val, index) => (index + 1) % 5 === 0 ? index + 1 + " *" : index + 1);
console.log(result.join(' '));