簡體   English   中英

如何用JavaScript刪除html標簽只保留BR,B和I標簽?

[英]How to remove html tags with JavaScript keep only BR, B and I tags?

當用戶單擊按鈕將其刪除並僅保留BR B和I標記時,我想從div中刪除富文本。 我已經嘗試了函數replace(/<\\/?[^>]+(>|$)/g, "")但它刪除了所有標簽。

<div id="content" contenteditable></div>
<button id="remove">Remove</button>

<script>
$(document).on('click', '#remove', function(e) {
    var a = $("#content").html();
    a = a.replace(/<\/?[^>]+(>|$)/g, "");
    $("#content").html(a);
});
</script>

示例輸入
<p>paragraph 1 <b>bold</b></p><br><br><p>paragraph 2 <i>italic</i></p>

我想要的是
paragraph 1 <b>bold</b><br><br>paragraph 2 <i>italic</i>

僅保留BR B和I標簽

嘗試使用.replace()函數參數返回空字符串,如果“b”或“br”,不區分大小寫,在匹配中找不到

 $(document).on('click', '#remove', function(e) { var a = $("#content").html(); a = a.replace(/<\\/?[^>]+(>|$)/g, function(match) { return !/br|b/i.test(match) ? "" : match }); $("#content").html(a); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="content" contenteditable> <p>paragraph 1 <b>bold</b></p><br><br><p>paragraph 2</p> </div> <button id="remove">Remove</button> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM