How can I remove HTML tags other than div and span from a string in JavaScript?

Viewed 598

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>
3 Answers

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'));

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);

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);

Related