Reputation: 1037
I need a regular expression (or any other thing) object that will match a character, and multiple instances of the same character following that, until it reaches a new character.
Ideally, I need a function that would return an array of all the consecutive characters found in the input string. It should return something like this.
> like_characters("Hello?");
Array ["H", "e", "ll", "o", "?"]
> like_characters("1234442332111???");
Array ["1", "2", "3", "444", "2", "33", "2", "111", "???"]
I don't have to use a regular expression--any way of "splitting" a string by a character change would work. It preferably would be a low-byte code, as I am working on a group project with a limited amount of space.
str.split(/\d*/)
str.split(/\d+/)
/(\d)+\1/
This is pretty much all I've got (and frankly, I'm surprised I even got this far--the realm of the regular expression is so murky).
Upvotes: 1
Views: 1106
Reputation: 156662
function splitWithRepeats(str) {
return str.match(/(.)\1*/g);
}
splitWithRepeats('Hello!'); // => ["H", "e", "ll", "o", "!"]
splitWithRepeats('Heeeelllllloooooo!'); // => ["H", "eeee", "llllll", "oooooo", "!"]
Upvotes: 2
Reputation: 255155
The regex would be as easy as
.match(/(.)\1*/g)
What it does - it matches a character and any number (including zero) of the same characters followed.
"Hello?".match(/(.)\1*/g)
// ["H", "e", "ll", "o", "?"]
Upvotes: 5