繁体   English   中英

消除错误 <br> 来自textarea的标签

[英]Remove errant <br> tags from textarea

我在SharePoint 2013中使用了textarea富文本编辑器文本编辑器,它有一个令人讨厌的习惯,将额外的break标记添加到幕后html标记中,像这样在标记的末尾:

<h1>Some heading<br></h1>
<p>Intro paragraph with maybe an actual.<br>That is supposed to be here.</p>
<ul>
   <li>Item 1</li>
   <li>Item 2</li>
   <br>
   <br>
</ul>

在此示例中,段落中间的br是用户插入的br,但是不希望在h1和ul标签末尾使用br,我希望将其删除。 我想不出
就在另一个结束标记有效之前,所以这是我的计划。

我想在所有其他结束标记之前立即找到所有br标记,并将其删除。

我们可以使用香草javascript,但是jQuery已经在页面上用于其他功能。

我发现此线程提供了一个正则表达式解决方案,可以在结束h2之前删除br。 它是php,提供的算法多于实现。 那里还有第二种解决方案,“使用DOM解析器”。 但是我对此并不熟悉。

另外,一些添加的标签是<br> ,有些是<br /> 并且可能有也可能没有行返回和空格。

是否有一种方法可以在查找其他所有有效的结束标记之前(忽略任何行返回或空格)而立即查找所有<br><br />

使用jQuery覆盖显示的情况。 可以添加到其中,发现其他未涵盖的情况

 // get html string from main editor and put in temporary div const $html = $('<div>').append($('#editor').html()) let ctr = 0; // counter for demo/debugging only // hunt for unwanted culprits $html.find('br').each(function() { const $br = $(this); // remove at end of parent OR more than one together OR is in a UL as child if (!this.nextSibling || $br.next().is('br') || $br.parent().is('ul')) { ctr++ this.remove(); } }) console.log('removed =', ctr) console.log($html.html()) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="editor"> <h1>Some heading<br></h1> <p>Intro paragraph with maybe an actual.<br>That is supposed to be here.</p> <ul> <li>Item 1</li> <li>Item 2</li> <br> <br> </ul> </div> 

如果字符串中包含HTML,则简单的RegEx替换即可删除您想要的内容:

htmlSourceCodeVar = htmlSourceCodeVar.replace(/<br(?: \/)?>(<\/)/ig, '$1');

什么正则表达式匹配是所有<br任选接着/接着></ ; 然后将其替换为该结束标记的开头,从而删除中断。 在这种情况下,您也可以在没有反向引用的情况下执行此操作,因为结束标记的开始是恒定的并且是已知的:

htmlSourceCodeVar = htmlSourceCodeVar.replace(/<br(?: \/)?><\//ig, '</');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM