Reputation: 2495
I'm trying to replace new line characters (\n) with html
tag's. But this should not happen if the line ends with an another html tag.
Like this:
Line 1<br />
Line 2<br />
<p>Hello World</p>\n
Line 4<br />
So my question now is why isn't the following regex working? Now are on every line
tags not just on the lines without the <\p> tag.
/(?!<.*>)\n/g
That regex is working if I dont want to have a <\br> tag if the next line doesnt contain html tags.
/\n(?!.*<.*>)/g
Upvotes: 0
Views: 123
Reputation: 43189
You need some logic with the following expression here:
.+<[^\n\r]+>$|(.+)
In JavaScript
:
var html = `Line 1
Line 2
<p>Hello World</p>
Line 4`;
var converted = html.replace(/.+<[^\n\r>]+>$|(.+)/gm, function(match, group1) {
if (typeof(group1) == "undefined") return match;
else return group1 + "<br>";
});
console.log(converted);
The idea is to match lines ending with a potential tag but to capture those without, see a demo on regex101.com.
Upvotes: 1