thmspl
thmspl

Reputation: 2495

Regex check character before new line is not working

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

Answers (1)

Jan
Jan

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

Related Questions