簡體   English   中英

javascript刪除html標記,但不刪除其中的內容,不<a >使用正則表達式標記</a>

[英]javascript remove html tags but not content within them and not <a > tags with regex

如何刪除字符串中的所有標簽,但不刪除<a> 而不是其中的文字?

例如: <em>Bold</em><a>Go here</a>應為: Bold<a>Go here</a>

您可以使用以下命令刪除<a></a>以外的所有類似於<...>字符串:

<(?!\/?a>)[^>]*>

觀看演示

不要忘記添加一個/i不區分大小寫的修飾符,以免匹配<A> 如果您不打算繼續關閉</a> ,則可以使用<(?!a>)[^>]*>

嘗試這個:

function strip_tags(input, allowed) {
  allowed = (((allowed || '') + '')
    .toLowerCase()
    .match(/<[a-z][a-z0-9]*>/g) || [])
    .join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
  var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
    commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
  return input.replace(commentsAndPhpTags, '')
    .replace(tags, function($0, $1) {
      return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
    });
}

var html = 'some html code';
html = strip_tags(html, '<a>');

來源: http//phpjs.org/functions/strip_tags/

暫無
暫無

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

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