jQuery/JS,删除/修剪尾部 html 换行符?
我正在寻找一些关于删除尾随 html 的最有效方法的想法 <br/>使用 javascript 或 jquery 标记。
规则:
- 必须删除前面和末尾的 br。
- 它必须删除非关闭和自关闭 br 标签。
- 文本内容中的所有 br 都必须保持不变。
HTML:
<div class="generatedContent">
<br>My awesome content.
<br><br>Some More awesome content.
<br>
<br>
<br>I still need the content written here<br/>
<br>
<br>
<br>
<br>
<br>
<br>
</div>
所需输出:
<div class="generatedContent">
My awesome content.
<br><br>Some More awesome content.
<br>
<br>
<br>I still need the content written here
</div>
I'm looking for some ideas for the most efficient way to remove trailing html <br/> tags using javascript or jquery.
RULES:
- The br, at the front and end must be removed.
- It must remove non-closing and self-closing br tags.
- All br within the textual content must remain untouched.
THE HTML:
<div class="generatedContent">
<br>My awesome content.
<br><br>Some More awesome content.
<br>
<br>
<br>I still need the content written here<br/>
<br>
<br>
<br>
<br>
<br>
<br>
</div>
THE DESIRED OUTPUT:
<div class="generatedContent">
My awesome content.
<br><br>Some More awesome content.
<br>
<br>
<br>I still need the content written here
</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
无法理解为什么您想为此使用正则表达式,就像大多数答案一样。在这里使用 DOM 方法很简单:
Can't understand why you'd want to to use regular expressions for this, as most answers are. Using DOM methods is easy here:
试试这个:
我已经尝试过了,它似乎可以在 FF 和 IE7 中工作。
Try this:
It seems to work in FF and IE7, that I've tried.
可能可以改进,但它应该有效:
Could probably be improved but it should work:
很简单。获取 generatedContent div 的 HTML,然后应用以下正则表达式:
使用纯 JS 可能有更有效的方法,但这可能更简洁。
Pretty simple. Take the HTML of the generatedContent div then apply the following regex:
There's probably a more efficient way to do it using pure JS, but this is probably more succint.
这是一个在 Firefox 中适用于我的非正则表达式解决方案。可能可以使用一些更好的边缘情况处理,但这个想法是有效的。基本上它只是找到第一个和最后一个非空文本节点并删除之前和之后的所有节点。
Here is a non regex solution that works for me in Firefox. Could probably use some better edge case handling but the idea works. Basically it just finds the first and last non-empty text nodes and removes all nodes before and after.