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
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.
Try this
var num = 123456789+"";// converting the number into string
var x1=num[0]+num[1]+num[2];//storing the individual values
var y1=new Array(x1);// creating a first group out of the first 3 numbers
var x2=num[3]+num[4]+num[5];
var y2=new Array(x2);// creating a second group out of the next 3 numbers
var x3=num[6]+num[7]+num[8];
var y3=new Array(x3);// creating a third group out of the next 3 numbers
var result=y1.concat(y2,y3);// concat all the 3 array
document.write(result);you get the output in the form of array
document.write("<br/>");
document.write(result[0]);
document.write("<br/>");
document.write(result[1]);
document.write("<br/>");
document.write(result[2]);
check the below link for the working example http://jsfiddle.net/informativejavascript/c6gGF/4/
精彩评论