Reputation: 6856
I need to remove from HTML line all tags except div and span. How can i do this ?
example
const str = "<div><p></p><span></span></div>";
remove(str)//<div><span></span></div>
Upvotes: 3
Views: 1309
Reputation: 15213
To remove all tags excluding specific tags, you can use the following regular expression.
const str = "<div><p></p><span></span></div>";
console.log(str.replace(/(<\/?(?:span|div)[^>]*>)|<[^>]+>/ig, '$1'));
Upvotes: 2
Reputation: 3910
You can use regex /<\/?(?!\bdiv\b)(?!\bspan\b)\b\w+\b>/g
with replaceAll
let str = "<div><oz></oz><span></span><hjk></hjk></div>";
let str1 = str.replaceAll(/<\/?(?!\bdiv\b)(?!\bspan\b)\b\w+\b>/g,'')
console.log(str1);
Upvotes: 1
Reputation: 42304
One option would be to use DomParser
's parseFromString()
method to parse the string as (temporary) HTML. You can then delete the target elements with .remove()
, and finally convert back to a string with toString()
if required:
const str = "<div><p></p><span></span></div>";
var parser = new DOMParser();
var htmlDoc = parser.parseFromString(str, 'text/html').body;
var spans = htmlDoc.getElementsByTagName('span');
for (var i = 0; i < spans.length; i++) {
spans[i].remove();
}
var parsed = htmlDoc.innerHTML.toString();
console.log(parsed);
Upvotes: 0