0

I'm trying to remove all style rules like this <style>blablabla</style> including <style> tag. I'm using the following script to accomplish this

  var text = '<   style  type= "text/css"  > hello1  <  /  sTyle  > 
               some text
              <   style  type= "text/css"  > hello2  <  /  sTyle  >';

  var regX = /< *style .*>([\s\S]*?)< *\/ *style *>/ig;
  text.replace(regX, "");

but it removes the whole text including "some text" between two style definitions. I want to keep "some text" in this example.

2 Answers 2

1

The problem is here

< *style .*>

The .* matches everything.

Change your regex to

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

or

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

Note, however that currently your regex misses cases, for example

<style></style>

You may consider using an actual HTML parser.

Sign up to request clarification or add additional context in comments.

Comments

1

It's best to avoid this .* greedy fellow in a RegEx. Try something like:

text.replace(/< *style[\w"= \/]*>[\w ]*<[ \/]*style *>/ig, '')

DEMO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.