替换除<strong>,</strong>,<b>和</b>

时间:2015-04-22 10:00:29

标签: javascript regex strip-tags

在JavaScript中,我使用此正则表达式从文本字符串中删除所有HTML标记:

t.replace(/<\/?[^>]+>/g, '');

现在我需要相同的东西,但它应该保留以下标签(它们不应该被替换):

<strong>
</strong>
<b>
</b>
你能帮帮我吗?我通常不使用正则表达式,所以如果这听起来太简单,请原谅。

3 个答案:

答案 0 :(得分:4)

只需使用否定的先行断言。

&#13;
&#13;
var s = '<strong> </strong>\n<b> </b> <h1> <h2> <a href="foo.com">';
alert(s.replace(/<(?!\/?b>|\/?strong>)[^>]+>/g, ''));
&#13;
&#13;
&#13;

开始时的

(?!\/?b>|\/?strong>)否定前瞻声称匹配,即<不会被/b>b>/strong>strong>字符串。

RegEx DEMO

答案 1 :(得分:1)

你也可以试试这个:

t.replace(/<(?!\/?(b|strong)(?=>|\s.*>))\/?.*?>/g, '')

答案 2 :(得分:1)

我会通过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()来选择更脏的版本。

相关问题