[英]How to remove html tags with JavaScript keep only BR, B and I tags?
I want to remove rich text from the div when user click the button to remove it and preserve only BR B and I tags. 当用户单击按钮将其删除并仅保留BR B和I标记时,我想从div中删除富文本。 I have tried the function
replace(/<\\/?[^>]+(>|$)/g, "")
but it removes all tags. 我已经尝试了函数
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>
Example input 示例输入
<p>paragraph 1 <b>bold</b></p><br><br><p>paragraph 2 <i>italic</i></p>
What i want 我想要的是
paragraph 1 <b>bold</b><br><br>paragraph 2 <i>italic</i>
preserve only BR B and I tags
仅保留BR B和I标签
Try using function parameter of .replace()
to return empty string if "b" or "br" , case insensitive, not found in match 尝试使用
.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.