使用JS删除额外的br标签

时间:2023-01-14 15:24:26

I have a post which contains extra line breaks and want to limit the post to only show one linebreak. I thought this css might work..

我有一个帖子,其中包含额外的换行符,并希望限制帖子只显示一个换行符。我以为这个CSS可能有效..

br+br{display:none}

but since the text is not wrapped in its own element all the line breaks in the post are siblings and this doesn't work... now I am trying to solve this with JS...

但由于文本没有包含在自己的元素中,帖子中的所有换行符都是兄弟姐妹而且这不起作用...现在我试图用JS解决这个问题...

content.replace(/<br><br>/g,'<br>')

Why is this only replacing the first set of linebreaks that are next to each other? (I need to run it multiple times to get the effect I want of all uneccesary line breaks being removed) and what should I do instead?

为什么这只替换了彼此相邻的第一组换行符? (我需要多次运行才能获得我想要删除所有不必要的换行符的效果)我该怎么做呢?

1 个解决方案

#1


3  

If your regex represents your HTML exactly, this should work:

如果你的正则表达式完全代表你的HTML,这应该工作:

content.replace(/(<br>)+/g,'<br>')

Although your CSS should've worked: http://jsfiddle.net/UvVbE/

虽然你的CSS应该有用:http://jsfiddle.net/UvVbE/

#1


3  

If your regex represents your HTML exactly, this should work:

如果你的正则表达式完全代表你的HTML,这应该工作:

content.replace(/(<br>)+/g,'<br>')

Although your CSS should've worked: http://jsfiddle.net/UvVbE/

虽然你的CSS应该有用:http://jsfiddle.net/UvVbE/