I guess it’s trivial but I’m struggling with the following situation:
String (HTML delievered as text):
text<br>text<br><ul><li>text</li></ul><br>
Now I need to replace every text<br>
with <div>text</div>
except if text is inside <li>/<ul>
.
.replace(/(.*?)<br>/g, '<div>$1</div>')
This works fine but how to prevent <ul><li>text</li></ul><br>
from beeing replaced?
3
Answers
This was my attempt before asking for a (shorter) regex solution:
Cause I'm splitting the string at
<br>
the tag itself gets lost. So if no substr exists (empty line) I write<br>
as substr and empty lines are getting parsed as<div><br></div>
. But I was not able to catch an empty line after<ul>
:In that case substr exists and the empty line gets lost.
If you prefer using regex use /(?!<li.?>)(?!</li>)(?!<ul.?>)(?!</ul>)(.?)
/g*
But it would be better if you switch to HTML parser to easily navigate and modify the structure of the HTML content
"You can’t parse [HTML] with regex. […] Have you tried using an [HT]ML parser instead?"™
(a terser version can be found in the snippet below)
Try it: