How To Remove Trailing Html Break From String?
Solution 1:
If you want to remove all trailing <br>
s, then use a quantifier:
/(<br>\s*)+$/
\s
matches any white space characters, so even if there is line break between continuous <br>
s, it will still match.
Solution 2:
If it's the contents of an HTML element, you can just use jQuery to remove the element:
$('#container').children('br').last().remove();
If it's a string, you can do something like this (still leveraging jQuery):
var cleaner = $('<div />').html(mystring);
cleaner.children('br:last-child').remove();
mystring = cleaner.html();
I prefer this over splitting on a string or your current RegEx because you're not handling the scenario of a BR tag like this: <br />
.
http://jsfiddle.net/TTg3p/
Solution 3:
I tested your code, and it seems to work. I pasted the following into a file and then viewed in firefox, and clicked view source. The second br was not visible in the source.
<html><body><script>var mystring = 'This is a string<br>\n next line<br>'
mystring=mystring.replace(/<br>$/,'');
document.write(mystring);
</script></html>
Perhaps your mystring variable has an actual linebreak (\n) at the end of it after the br, so your regular expression is not matching?
Post a Comment for "How To Remove Trailing Html Break From String?"