Reputation: 909
On JavaScript, it can remove all HTML tags in the text with regular expressions like this:
replace(/(<([^>]+)>)/ig, "")
In addition, I would like to keep specific tags.
ex)<h1>Text</h1><input type="text">Text</input><b>Text</b> → <h1>Text</h1>Text<b>Text</b>
I tried this code, but it doesn't work correctly.
replace(/<\/{0,1}!(font|h\d|p|hr|pre|blockquote|ol|ul|...).*?>/ig, "");
Please let me know the best formula.
Upvotes: 1
Views: 62
Reputation: 786111
You need to use negative lookahead:
replace(/<\/?(?!(font|h[1234]|p|hr|input|pre|blockquote|ol|ul))[^>]*>/ig, "");
Caution: HTML parsing and manipulation is error prone using regex like this. Better to use DOM parsers.
Upvotes: 0
Reputation: 193301
What about using such a simple function to remove unwanted tags:
function sanitize(text, allowed) {
var tags = typeof allowed === 'string' ? allowed.split(',') : allowed;
var a = document.createElement('div');
a.innerHTML = text;
for (var c = a.childNodes, i = c.length; i--;) {
if (c[i].nodeType == 1) {
c[i].innerHTML = sanitize(c[i].innerHTML, tags);
if (tags.indexOf(c[i].tagName.toLowerCase()) === -1) {
c[i].parentNode.removeChild(c[i]);
}
}
}
return a.innerHTML;
}
sanitize('<h1>This is a <script>alert(1)</script> test</h1> <input type="text"> and <b>this</b> should stay.', 'font,h1,h2,p,b,ul')
Output:
"<h1>This is a test</h1> and <b>this</b> should stay."
Or you can replace tag with it's text content if you use
c[i].parentNode.replaceChild(document.createTextNode(c[i].innerText);
instead of c[i].parentNode.removeChild(c[i]);
Upvotes: 0
Reputation: 324800
Especially in JavaScript, there is no excuse.
var div = document.createElement('div');
div.innerHTML = your_input_here;
var allowedtags = "font|h[1-6]|p|hr|...";
var rgx = new RegExp("^(?:"+allowedtags+")$","i");
var tags = div.getElementsByTagName('*');
var length = tags.length;
var i;
for( i=length-1; i>=0; i--) {
if( !tags[i].nodeName.match(rgx)) {
while(tags[i].firstChild) {
tags[i].parentNode.insertBefore(tags[i].firstChild,tags[i]);
// this will take all children and extract them
}
tags[i].parentNode.removeChild(tags[i]);
}
}
var result = div.innerHTML;
Upvotes: 1