Mike
Mike

Reputation: 980

how to remove trailing html break from string?

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>

Upvotes: 4

Views: 5527

Answers (5)

user670839
user670839

Reputation:

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>

Upvotes: 0

Martin Borthiry
Martin Borthiry

Reputation: 5326

Try this:

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

demo :)

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816404

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

Upvotes: 14

anorakgirl
anorakgirl

Reputation: 788

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?

Upvotes: 0

Adam Terlson
Adam Terlson

Reputation: 12730

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/

Upvotes: 1

Related Questions