4

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.

mystring=mystring.replace(/<br>$/,''); 

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>
Mike
  • 980
  • 3
  • 15
  • 29

5 Answers5

14

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.

DEMO

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

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/

Adam Terlson
  • 12,610
  • 4
  • 42
  • 63
0

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>
0

Try this:

mystring.split('<br>').slice(0,-1).join('<br>');

demo :)

Martin Borthiry
  • 5,256
  • 10
  • 42
  • 59
0

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?

anorakgirl
  • 668
  • 8
  • 19