¿Cómo eliminar la ruptura de html final de la cadena?

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>

then the code above just returns

This is a string<br>
next line

preguntado el 08 de noviembre de 11 a las 19:11

5 Respuestas

If you want to remove all trailing <br>s, then use a quantifier:


\s matches any white space characters, so even if there is line break between continuous <br>s, it will still match.


respondido 08 nov., 11:23

/(<br\s*\/?\s*>\s*)+$/ This handles more cases like <br/>, <br />, <br / > - manojchowdary27

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);
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 />.


respondido 08 nov., 11:23

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.

var mystring = 'This is a string<br>\n next line<br>'

Perhaps your mystring variable has an actual linebreak (\n) at the end of it after the br, so your regular expression is not matching?

respondido 08 nov., 11:23

Yup. I just realized it's working. But my issue is with multiple trailing breaks. Doh. - Mike

@Mike: So you want to remove all trailing <br>s? Then use a quantifier: /(<br>\s*)+$/. - Felix Kling

Prueba esto:


manifestación :)

respondido 09 nov., 11:00

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>

Respondido 15 Abr '20, 23:04

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.