JS: How to remove style tags and their content from an HTML string, using regular expressions?

Viewed 4905

I need to remove the entire content of style tags from an html string, in multiple occurrences. I can't use a DOM parser for it.

How could i do this, in JavaScript?

4 Answers

For those that land here in 2020 this worked for me.

string.replace(/(<style[\w\W]+style>)/g, "")

As Bergi alluded to in the OP comments thought, this should be regarded as a last resort if there are no better options. RegEx is not the best way to deal with HTML.

    var string = "<style>someHTMLStuff</style> non style <html>stuff</html>"

    var s = string.replace(/<style.*?<\/style>/g, '')
    
    console.log(s);

I am assuming you wanted the entire style tag removed, not just its contents

Edit: quotes

To replace all style attributes in a HTML element (innerHTML) :

<div id="el">
  <p style="font-weight:bold">Line 1</p>
  <p style="color:red">Line 2</p>
</div>

//script
let element = document.getElementById('el')
element.innerHTML.replace(/style=\".*"/gm,'')

This will remove all elements style attribute in element by id el.

Related