2

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]
CostaCos
  • 59
  • 5
  • 1
    23 23 would not work here. It would have to be 2 3 2 3, no? With the same logic, shouldn't it be 10 10 10 rather than 1 0 1 0 1 0? – Kobe Aug 14 '19 at 13:47
  • 2
    I dont get the idea. And your example is a bit of confusing: how do you have 23s in it and not 01s? Either you have 01s and 23s or you have 0s, 1s, 2s, and 3s – lucifer63 Aug 14 '19 at 13:49
  • @Kobe you are right, I corrected it. Thank you – CostaCos Aug 14 '19 at 20:06

1 Answers1

14

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

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

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392