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
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.
You can achieve that using this: str = str. replace(/<br\s*\/?>/gi,' ');
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.
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.
This is simpler than you're thinking it out to be:
Text = Text.replace(new RegExp("</h2>(\<br \/\>)*", "g"), "</h2>");
You can also make this a little nicer? using the shorthand regex syntax
Text = Text.replace(/<\/h2>(<br\s*\/>)*/g, '</h2>');
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With