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 badges1 Answer
Reset to default 8Your regex is fine, you're just using the wrong function. Use String.match, not String.split:
var matches = 'aaaabbbbczzxxxhhnnppp'.match(/((.)\2*)/g);