how to remove all tags in a string but not <a>
? and not the text inside them?的JavaScript刪除HTML標籤而不是內容中他們並沒有<a > tags with regex
For example: <em>Bold</em><a>Go here</a>
should be: Bold<a>Go here</a>
how to remove all tags in a string but not <a>
? and not the text inside them?的JavaScript刪除HTML標籤而不是內容中他們並沒有<a > tags with regex
For example: <em>Bold</em><a>Go here</a>
should be: Bold<a>Go here</a>
You can remove all strings that look like <...>
other than <a>
or </a>
with
<(?!\/?a>)[^>]*>
See demo
不要忘記添加/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>');
你想操作字符串,或DOM?爲什麼要標記正則表達式?根據第一個問題,你可能不需要它們。 – cmbuckley
你[不應該](http://stackoverflow.com/a/1732454/1169519)... – Teemu