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>
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>
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'));
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);
for loop. getElementsByTagName returns a live collection. See stackoverflow.com/questions/23988982/…