![](/img/trans.png)
[英]Using replace to remove <strong> tags from html
[英]Replace all HTML tags except for <strong>, </strong>, <b> and </b>
在JavaScript中,我使用此正則表達式從文本字符串中刪除所有HTML標簽:
t.replace(/<\/?[^>]+>/g, '');
現在,我需要同樣的東西,但是它應該保留以下標簽(不應替換它們):
<strong>
</strong>
<b>
</b>
你能幫助我嗎? 我通常不使用正則表達式,所以如果這聽起來太簡單,請原諒。
只需使用否定的超前斷言即可。
var s = '<strong> </strong>\\n<b> </b> <h1> <h2> <a href="foo.com">'; alert(s.replace(/<(?!\\/?b>|\\/?strong>)[^>]+>/g, ''));
(?!\\/?b>|\\/?strong>)
開頭的否定表示匹配,即<
不會跟着/b>
或b>
或/strong>
或strong>
字符串。
您也可以嘗試以下方法:
t.replace(/<(?!\/?(b|strong)(?=>|\s.*>))\/?.*?>/g, '')
我將通過DOM解決此問題:
var s = '<ol><li>hello </li><li><b>world</b></li></ol>'; var node = document.createElement('div'); node.innerHTML = s; function clean(node, allowed, target) { for(var i = 0; i < node.childNodes.length; ++i) { var child = node.childNodes[i]; if (child.nodeType === 1) { clean(child, allowed, target); if (allowed.indexOf(child.nodeName) === -1) { [].forEach.call(child.childNodes, function(item) { target.appendChild(item); }); node.removeChild(child); --i; } } } } clean(node, ['STRONG', 'B'], node); console.log(node.innerHTML);
您還可以通過JavaScript中的strip_tags()
實現選擇較臟的版本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.