MiloŇ° MiloŇ° - 3 months ago 12
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: http://jsfiddle.net/JwrZ6/1/

How can I keep the delimiter?

Jon Jon
Answer

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)