Javascript .split() a string for each number of characters

javascriptstring

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 passed in.

Thanks

Best Answer

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.