i.brod
i.brod

Reputation: 4603

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

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?

Upvotes: 5

Views: 8959

Answers (4)

Jason Deppen
Jason Deppen

Reputation: 300

<style([\S\s]*?)>([\S\s]*?)<\/style>

https://regex101.com/r/C28OPE/1

This worked for me even with multiple tags. credit

Upvotes: 4

swina
swina

Reputation: 217

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.

Upvotes: -2

JD Guzman
JD Guzman

Reputation: 378

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.

Upvotes: 11

Kaelan Mikowicz
Kaelan Mikowicz

Reputation: 355

    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

Upvotes: 6

Related Questions