0

have a var id = "123456789";

how to split in into groups after each 3 digits??

result must be like this:

var no1 = 123;
var no2 = 456;
var no3 = 789;

if the id will be longer 12, 15 or more digits, should work the same!

r.r
  • 7,023
  • 28
  • 87
  • 129

4 Answers4

3

this can be your answer, use this function per your need, the output array contains the result

function parseDigits()
{
    var number = 123456789,
    output = [],
    sNumber = number.toString();

    for (var i = 0, len = sNumber.length; i < len; i += 3) {
        output.push(+sNumber.charAt(i)+sNumber.charAt(i+1)+sNumber.charAt(i+2));
    }

    alert(output);

}
n8coder
  • 691
  • 4
  • 12
  • thanks for help, i had a stress with such a simple thing, but it works pretty to me now! – r.r Jul 17 '13 at 12:25
1

Can this work ?

var id = "123456789"
var arr = id.match(/.{1,3}/g);

Here:

arr[0] == "123"
arr[1] == "456" ....

Better to get the values using substring(). Do check for the length before performing substring() to save yourself from IndexOutOfBounds sort of errors.

AllTooSir
  • 48,828
  • 16
  • 130
  • 164
1
var splittedArray = yourString.match(/.../g);

that way you'll get the array of all your values :)

Gintas K
  • 1,438
  • 3
  • 18
  • 38
1
var result = [];
for(var i = 0; i < id.length; i+=3){
    result.push(id.substring(i, i + 3));
}

If you want exact result(stored in no variables):

for(var i = 0, j = 1; i < id.length; i+=3, j++){
    window['no' + j] = id.substring(i, i + 3);
}

console.log(no1);
console.log(no2);
console.log(no3);
karaxuna
  • 26,752
  • 13
  • 82
  • 117