如何从字符串中删除尾随的HTML断行

how to remove trailing html break from string?

本文关键字:HTML 断行 删除 字符串      更新时间:2023-09-26

我下面有一个字符串,我想删除尾随的
,但我很挣扎。任何帮助吗?

This is a string<br>    
next line<br>

在我的函数之后,字符串应该是

This is a string<br>
next line

执行下面的代码似乎不起作用。好吧,它工作,但它不清除两个尾随休息。

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

所以如果我的字符串实际上是:

This is a string<br>
next line<br>
<br>

那么上面的代码只返回

This is a string<br>
next line
<br>

如果要删除所有尾随的<br>,则使用量词:

/(<br>'s*)+$/

's匹配任何空格字符,因此即使连续的<br> s之间有换行符,它仍然匹配。

如果它是HTML元素的内容,您可以使用jQuery删除该元素:

$('#container').children('br').last().remove();

如果它是一个字符串,你可以这样做(仍然使用jQuery):

var cleaner = $('<div />').html(mystring);
cleaner.children('br:last-child').remove();
mystring = cleaner.html();

我更喜欢这个分割字符串或您当前的RegEx,因为您没有处理像这样的BR标记的场景:<br />

http://jsfiddle.net/TTg3p/

我测试了你的代码,它似乎工作。我将以下内容粘贴到一个文件中,然后在firefox中查看,并单击查看源代码。第二个br在源文件中不可见。

<html>
<body>
<script>
var mystring = 'This is a string<br>'n next line<br>'
mystring=mystring.replace(/<br>$/,''); 
document.write(mystring);
</script>
</html>

也许你的mystring变量在br之后的末尾有一个实际的换行符('n),所以你的正则表达式不匹配?

试试这个:

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

演示:)

如果你想删除元素中最后一个尾随的<br>,你可以使用:

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>