15

I am trying to split a string by a single or multiple occurrence of letters.

For example:

aaabbcapppp, would yield the array, ["aaa", "bb", "c", "a", "pppp"]

The most-Inefficient idea I had was to just utilize, newArray = str.split(""); and rebuild the array to my needs. I assume there is a much more efficient solution.

1

2 Answers 2

31

Something like this would work:

"aaabbcapppp".match(/(.)\1*/g) // ["aaa", "bb", "c", "a", "pppp"]

The (.) matches any single character, captured in group 1, followed by that same character repeated zero or more times (\1 is a backreference which matches exactly what was matched in group 1).

To match only Latin letters, consider using [a-z], for example:

"aaa-bbca!!pppp".match(/([a-z])\1*/g) // ["aaa", "bb", "c", "a", "pppp"]

Here, the - and !! are not included in the result array.

0
1

The regex solution is probably the way to go, but if for some reason you want to do it manually, something like this would work

function charSplit(str) {
    var arr = [], l, j = -1;
    for (var i=0; i<str.length; i++) {
        var c = str.charAt(i);
        l==c ? arr[j] += c : arr[++j] = c;
        l=c;
    }
    return arr;
}

FIDDLE

2
  • +1 Seems like this might possibly be improved by finding the index of the first and last character in a run then doing a substring rather than concatenation. I like it though.
    – p.s.w.g
    Feb 24, 2014 at 20:04
  • @p.s.w.g - Thanks, +1 to you to. And yes, it could probably be improved, but this was as simple as I could get it, I even minified it for fun -> jsfiddle.net/MJQM8/1
    – adeneo
    Feb 24, 2014 at 20:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.