I have a string below and I want to remove the trailing
but I'm struggling. Any help?
This is a string<br> next line<br>
So after my function, the string should be
This is a string<br> next line
Doing this code below doesn't seem to be working. Well, it works but it doesn't clear out two trailing breaks.
So if my string is actually:
This is a string<br> next line<br> <br>
then the code above just returns
This is a string<br> next line <br>
preguntado el 08 de noviembre de 11 a las 19:11
If it's the contents of an HTML element, you can just use jQuery to remove the element:
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:
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?
If you want to remove the last trailing
<br> inside an element, you can use this:
const element = document.getElementById('element') console.log('Before:', element.innerHTML) const last = element.childNodes[element.childNodes.length - 1] if (last.tagName === 'BR') last.remove() console.log('After:', element.innerHTML)
<div id="element">Some text<br>other text<br></div>