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>

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

1 Comment

/(<br\s*\/?\s*>\s*)+$/ This handles more cases like <br/>, <br />, <br / >
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/

Comments

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?

2 Comments

Yup. I just realized it's working. But my issue is with multiple trailing breaks. Doh.
@Mike: So you want to remove all trailing <br>s? Then use a quantifier: /(<br>\s*)+$/.
0

Try this:

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

demo :)

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.