kman
kman

Reputation: 2257

Javascript Regex to split a string into array of grouped/contiguous characters

I'm trying to do the same thing that this guy is doing, only he's doing it in Ruby and I'm trying to do it via Javascript:

Split a string into an array based on runs of contiguous characters

It's basically just splitting a single string of characters into an array of contiguous characters - so for example:

Given input string of

'aaaabbbbczzxxxhhnnppp'

would become an array of

['aaaa', 'bbbb', 'c', 'zz', 'xxx', 'hh', 'nn', 'ppp']

The closest I've gotten is:

    var matches = 'aaaabbbbczzxxxhhnnppp'.split(/((.)\2*)/g);
    for (var i = 1; i+3 <= matches.length; i += 3) {
        alert(matches[i]);
    }

Which actually does kinda/sorta work... but not really.. I'm obviously splitting too much or else I wouldn't have to eliminate bogus entries with the +3 index manipulation.

How can I get a clean array with only what I want in it?

Thanks-

Upvotes: 2

Views: 3521

Answers (1)

Ben Lee
Ben Lee

Reputation: 53319

Your regex is fine, you're just using the wrong function. Use String.match, not String.split:

var matches = 'aaaabbbbczzxxxhhnnppp'.match(/((.)\2*)/g);

Upvotes: 8

Related Questions