MiloŇ° MiloŇ° - 7 months ago 60
Javascript Question

Javascript and regex: split string and keep the separator

I have a string:

var string = "aaaaaa<br />&dagger; bbbb<br />&Dagger; cccc"

And I would like to split this string with the delimiter
<br />
followed by a special character.

To do that, I am using this:

string.split(/<br \/>&#?[a-zA-Z0-9]+;/g);

I am getting what I need, except that I am losing the delimiter.
Here is the example:

How can I keep the delimiter?

Jon Jon

Use positive lookahead so that the regular expression asserts that the special character exists, but does not actually match it:

string.split(/<br \/>(?=&#?[a-zA-Z0-9]+;)/g);

See it in action.

Update: fixed typo (moved literal ; inside lookahead parens)