Tom Gullen
Tom Gullen

Reputation: 61755

Javascript regexp replace all <br />'s

I'm trying to replace any <br /> tags that appear AFTER a </h2> tag. This is what I have so far:

Text = Text.replace(new RegExp("</h2>(\<br \/\>.+)(.+?)", "g"), '</h2>$2');

It doesn't seem to work, can anyone help? (No matches are being found).

Test case:

<h2>Testing</h2><br /><br /><br />Text

To:

<h2>Testing</h2>Text

Upvotes: 5

Views: 22226

Answers (4)

mu is too short
mu is too short

Reputation: 434785

If you have jQuery kicking around then you can do this safely without regular expressions:

var $dirty = $('<div>').append('<p>Where is<br>pancakes</p><h2>house?</h2><br><br>');
$dirty.find('h2 ~ br').remove();
var clean = $dirty.html();
// clean is now "<p>Where is<br>pancakes</p><h2>house?</h2>"

This will also insulate against the differences between <br>, <br/>, <br />, <BR>, etc.

Upvotes: 5

serby
serby

Reputation: 4316

You can also make this a little nicer? using the shorthand regex syntax

Text = Text.replace(/<\/h2>(<br\s*\/>)*/g, '</h2>');

Upvotes: 3

serby
serby

Reputation: 4316

This would do what you are asking:

Text = Text.replace(new RegExp("</h2>(<br />)*", "g"), '</h2>');

Upvotes: 5

mVChr
mVChr

Reputation: 50205

This is simpler than you're thinking it out to be:

Text = Text.replace(new RegExp("</h2>(\<br \/\>)*", "g"), "</h2>");

Upvotes: 16

Related Questions