JS string.split() without removing the delimiters

Martin Janiczek picture Martin Janiczek · Dec 22, 2010 · Viewed 46.1k times · Source

How can I split a string without removing the delimiters?

Let's say I have a string: var string = "abcdeabcde";

When I do var newstring = string.split("d"), I get something like this:

["abc","eabc","e"]

But I want to get this:

["abc","d","eabc","d","e"]

When I tried to do my "split2" function, I got all entangled in splice() and indexes and "this" vs "that" and ... aargh! Help! :D

Answer

Kai picture Kai · Dec 22, 2010

Try:

"abcdeabcde".split(/(d)/);