Search code examples
javascriptsplitchunks

How to split a string of numbers in to chunks in javascript


Lets say that i have a string with random numbers like the following one 11111111133333333333222222220000000111111010101010223311232323 and I would like to split the above string into chunks that each number forms and maybe put it in an array or an object (it does not matter).

The first solution that I have think so far is iterate over the string and if you find a different character from the previous one start pushing the current character in an object. The second solution that I have find is to replace each character transition in the string with the characters that do the transition plus with a space character in the middle, then split this string in the space character. The second solution is hard for me to implement, cause I can not think of the regular expression what would look like. The first solution is feasible but is too much coding and I'm hoping that something faster exists.

So an expected output would be a one dimensional Array where each cell will have the chunks of numbers like the following (for the above string).

[111111111, 33333333333, 22222222, 0000000,
111111, 0, 1, 0, 1, 0, 1, 0,
1, 0, 22, 33, 11, 2, 3, 2, 3, 2, 3]

Solution

  • You could match for a character and for following same group.

    var string = '11111111133333333333222222220000000111111010101010223311232323',
        result = string.match(/(.)\1*/g);
    
    console.log(result);