Edgar
Edgar

Reputation: 6856

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

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

Answers (3)

s.kuznetsov
s.kuznetsov

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

Rajdeep D
Rajdeep D

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

Obsidian Age
Obsidian Age

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

Related Questions