Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 754
adardesign Avatar asked May 16 '26 13:05

adardesign


1 Answers

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.

like image 74
outis Avatar answered May 18 '26 02:05

outis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!