admin管理员组

文章数量:1391925

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 bee 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-

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 bee 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-

Share Improve this question edited May 23, 2017 at 12:30 CommunityBot 11 silver badge asked Sep 21, 2011 at 5:31 kmankman 2,2673 gold badges25 silver badges49 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

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

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

本文标签: Javascript Regex to split a string into array of groupedcontiguous charactersStack Overflow