views:

382

answers:

1

I have a variable that holds a number

var simpleNumber = 012345678;

I want to .split() this number and create an array that would be of each 3 numbers

the array should look like this

[012, 345, 678]

var splitedArray = simpleNumber.toString().split(/*how do i split this?*/);

it is part of a getRGB("ffffff") function, so i cant know what will be past in.

Thanks

+8  A: 

You can try:

var splittedArray = "012345678".match(/.../g);

function tridigit(n) {
    return n.toString().match(/.{1,3}/g);
}

Note that if you prefix a number with a zero, it will be interpreted in octal. Octal literals are officially deprecated, but are supported for the time being. In any case, numbers don't have leading zeros, so it won't appear when you convert the number to a string.

Testing on Safari and FF, numbers with a leading 0 and an 8 or 9 are interpreted in base 10, so octal conversion probably wouldn't be a problem with your specific example, but it would be a problem in the general case.

outis
Note that this won't work as you expect if the number starts with a zero, as the zero disappears.
Andreas Bonini
Also, the leading 0 will turn the number into octal.
SLaks
Oh, I see, any solution for a case that it starts with a 0
adardesign
Will not work if the number is not a multiplication of 3 (in this case).
KooiInc
will i have to check if the leading no. is not a 0, and if yes increment it? is that a solution?
adardesign
@adardesign: Positional number systems have an infinite number of 0 digits running to the left of the numeral. Because they contribute nothing to the value the numeral, they're left out. If you want zeros, you'll have to figure out how many you want to add, because any other way isn't well defined.
outis
@adardesign: You need to better define what numbers you're working with. Is it just 12345678, or any number?
outis
it is part of a getRGB("ffffff") function, so i cant know what will be past in.anyway, Thanks.
adardesign