2

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-

1 Answer 1

8

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

var matches = 'aaaabbbbczzxxxhhnnppp'.match(/((.)\2*)/g);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.