Reputation: 3270
I want to sort this into groups of 1s and groups of zeros
var string = '10011110000100101';
var matches = string.match(/0*|1*/gi);
console.log(matches);
I currently get
["", "00", "", "", "", "", "0000", "", "00", "", "0", "", ""]
Expected output:
["1", "00", "1111", "0000", "1", "00", "1", "0", "1"]
The 1s aren't being grouped, and are showing up blank.
If I switch the one and zero, the opposite happens:
["1", "", "", "1111", "", "", "", "", "1", "", "", "1", "", "1", ""]
Upvotes: 0
Views: 39
Reputation: 76656
You're using the *
quantifier for both 0
and 1
. *
means "match the preceding token zero or more times". The regex matches an empty string, and that's reflected in your final output. To fix this, you can use +
, which means "match the preceding token one more times".
/(0+|1+)/
Upvotes: 2
Reputation: 413717
Use +
instead of *
:
var matches = string.match(/0+|1+/gi);
The problem is that 0*
matches a 1
in the string.
Upvotes: 1