[英]javascript remove html tags but not content within them and not <a > tags with regex
how to remove all tags in a string but not <a>
? 如何删除字符串中的所有标签,但不删除
<a>
? and not the text inside them? 而不是其中的文字?
For example: <em>Bold</em><a>Go here</a>
should be: Bold<a>Go here</a>
例如:
<em>Bold</em><a>Go here</a>
应为: Bold<a>Go here</a>
You can remove all strings that look like <...>
other than <a>
or </a>
with 您可以使用以下命令删除
<a>
或</a>
以外的所有类似于<...>
字符串:
<(?!\/?a>)[^>]*>
Do not forget to add a /i
case insensitive modifier to also avoid matching <A>
. 不要忘记添加一个
/i
不区分大小写的修饰符,以免匹配<A>
。 If you do not plan to keep closing </a>
, you can use <(?!a>)[^>]*>
. 如果您不打算继续关闭
</a>
,则可以使用<(?!a>)[^>]*>
。
Try this: 尝试这个:
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>');
source: http://phpjs.org/functions/strip_tags/ 来源: http : //phpjs.org/functions/strip_tags/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.