The example below results as expected:
const str = "abbcccddddeeeeeffffff";
const res = str.match(/(.)\1*/g);
console.log(res);
But if I try to group non consecutive letters:
const str = "abxbcxccdxdddexeeeefxfffffxx";
const res = str.match(/(.)\1*/g);
console.log(res);
I would like to get somethig like this:
[ 'a', 'bb', 'xxxxxxx', 'ccc', 'dddd', 'eeeee', 'ffffff']
Sort the string before applying the Regex :
const str = "abxbcxccdxdddexeeeefxfffffxx";
const res = [...str].sort().join('').match(/(.)\1*/g);
console.log(res);
If you absoloutely want them in that order, you can dedup the string and match the letters individually
const str = "abzzzbcxccdxdddexeeeefxfffffxx";
const res = [];
[...new Set(str)].forEach(letter => {
const reg = new RegExp(`${letter}`, "g");
res.push(str.match(reg).join(""));
});
console.log(res);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With