[SOLVED] JavaScript regex split consecutive string (vs Java)


This Content is from Stack Overflow. Question asked by Luka

I have this splitting regex to group consecutive words in String


So in Java the above regex would split the string as I’m expected like this

// return [aaa, bbb, cccc, dd]

but in JS the same regex will split like this, included my capture group 1

/// return ['aaa', 'a', 'bbb', 'b', 'cccc', 'c', 'dd']

So is there anyway to avoid capture group in result in JS (I’ve tried (?:…) but then I can’t use 1 anymore)

And if you have other way or improvement to split consecutive words in JS (using or not using regex), please share it, thank you.


I would keep your current logic but just filter off the even index list elements:

var input = "aaabbbccccdd";
var matches = input.split(/(?<=(.))(?!\1)/)
                   .filter(function(d, i) { return (i+1) % 2 != 0; });

This Question was asked in StackOverflow by Luka and Answered by Tim Biegeleisen It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?