Ernest Michael Ernest Michael - 1 year ago 119
Node.js Question

NodeJS - Loop through range as string

I'm trying to loop through a range of numbers in NodeJS, but not by using integers, by using a string.

For example, I want to loop through from 000000 to 500000. Ie. 000001, 000002, all the way to 500000. When percieved as an integer, NodeJS will just go 1, 2, all the way up to 500000. I want to keep if so the number always has 6 digits and loops through every possible number.

Edit: I need it to loop through like 000001, 000002, ..., 000010, ... , 000100, ... , 001000, ... , 010000, ... , 100000, ... , 500000. Filling in every number in between though

Thanks in advance

Answer Source

If you're using a relatively new version of node you can use string.padStart():

for(var i = 0; i <= 500000; i++) {
    str = i.toString().padStart(6, 0)
    // 000001, etc
}

More docs here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download