Javascript and regex: split string and keep the separator Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Javascript and regex: split string and keep the separator without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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?

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:

var string = "aaaaaa<br />&dagger; bbbb<br />&Dagger; cccc";
console.log(string.split(/<br />(?=&#?[a-zA-Z0-9]+;)/g));
We are here to answer your question about Javascript and regex: split string and keep the separator - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji