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 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);
本文标签: Javascript Regex to split a string into array of groupedcontiguous charactersStack Overflow
版权声明:本文标题:Javascript Regex to split a string into array of groupedcontiguous characters - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744672222a2618892.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论