Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 857
Tom Gullen Avatar asked Apr 28 '11 22:04

Tom Gullen


People also ask

How do I replace all line breaks in a string with BR elements?

The RegEx is used with the replace() method to replace all the line breaks in string with <br>. The pattern /(\r\n|\r|\n)/ checks for line breaks.

How do I replace my br tag?

You can achieve that using this: str = str. replace(/<br\s*\/?>/gi,' ');

How to replace line break in JavaScript?

To remove all line breaks from a string, call the replace() method on the string, passing it a regular expression that replaces all occurrences of the \r and \n characters with an empty string. The replace method returns a new string with the matched characters replaced.

How to replace string characters in JavaScript?

Answer: Use the JavaScript replace() method You can use the JavaScript replace() method to replace the occurrence of any character in a string. However, the replace() will only replace the first occurrence of the specified character. To replace all the occurrence you can use the global ( g ) modifier.


3 Answers

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

Text = Text.replace(new RegExp("</h2>(\<br \/\>)*", "g"), "</h2>");
like image 195
mVChr Avatar answered Sep 30 '22 18:09

mVChr


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

Text = Text.replace(/<\/h2>(<br\s*\/>)*/g, '</h2>');
like image 42
serby Avatar answered Sep 30 '22 20:09

serby


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.

like image 30
mu is too short Avatar answered Sep 30 '22 20:09

mu is too short