We help IT Professionals succeed at work.

Regular Expression to remove JavaScript / CSS from HTML source

Medium Priority
439 Views
Last Modified: 2013-11-19
So far I have a regex that I use to strip the HTML tags from a page however this doesnt work correctly with CSS and JavaScript...

Im looking for a regular expression to remove script (javascript, etc) and styles from the html source i have in a local string variable

examples of what i need to remove:

[style type="text/css"] blah [/style]
[style] blah [/style]
[script language="JavaScript"] blah [/script]
[script type="text/javascript"] blah [/script]

is this possible w/ regexp?
Comment
Watch Question

Author

Commented:
i'm using vb.net by the way (that is if there is a different method for doing this)
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015
Commented:
"\\[style.*?\\]/style\\]"
"\\[script.*?\\[/script\\]"
but are you sure that your tags use [] and not <>?

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts

Author

Commented:
i didn't know i could post < > on here so i just used [ ] instead...

Author

Commented:
hmm.. can you clean this up a bit with <> tags
ozo
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015

Commented:
"<style.*?</style>"
"<script.*?</script>

Author

Commented:
hmm, this doesn't seem to work:

here is the function returning a string

    Public Function RemoveStyleBlocks(ByVal strSource As String) As String
        Return Regex.Replace(strSource, "<style.*?</style>", "")
    End Function

i have a function that works for removing html tags for your reference, perhaps something else is required in your script/style regex?

    Public Function RemoveHTMLTags(ByVal strSource As String) As String
        Return Regex.Replace(strSource, "<[^>]*>", "")
    End Function
ozo
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015

Commented:
if strSource spans multiple lines
Regex.Replace(strSource,"<style.*?</style>", "",RegexOptions.Singleline)

Author

Commented:
ah great, that appears to work perfectly... thank you!
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.