最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

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

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

Share Improve this question edited Aug 26, 2013 at 21:08 adardesign asked Dec 23, 2009 at 15:01 adardesignadardesign 35.8k15 gold badges66 silver badges86 bronze badges 1
  • 8 A leading 0 in javascript creates a number in octal. If it is important, you need to represent it as a string. – Gabe Moothart Commented Dec 23, 2009 at 15:08
Add a ment  | 

2 Answers 2

Reset to default 12

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/informativejavascript/c6gGF/4/

发布评论

评论列表(0)

  1. 暂无评论