0

I want to remove <script> tags from an html string using regex.

I have the following code which works, but doesn't work when you put back to back scripts:

function removeScriptsFromHtmlStr(html) {
  const regex = /<script(?:(?!\/\/)(?!\/\*)[^'"]|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\/\/.(?:\n)|\/\*(?:(?:.|\s))*?\*\/)*?<\/script>/;
  const result = html.replace(regex, '');
  return result;
}

So for example:

running this through the funciton will work fine

<script>alert(document.cookie);</script>

but this won't:

<script>alert(document.cookie);</script><script>alert(document.cookie);</script>

How can I update the regex to fix this?

7
  • 1
    add a g flag (stands for global). So /your regex/g, otherwise only the first match will be replaced Commented Feb 18, 2020 at 19:36
  • 1
    Does this answer your question? Removing all script tags from html with JS Regular Expression Commented Feb 18, 2020 at 19:36
  • If this is done for security reasons, then don't do it with RegExp, it's far too easy to trick any RegExp you ever can create. Create a DocumentFragment instead, attach the HTML, and remove the script elements from the parsed fragment. Commented Feb 18, 2020 at 19:43
  • 1
    Don't parse HTML with regex. RegEx match open tags except XHTML self-contained tags Commented Feb 18, 2020 at 19:45
  • 1
    FYI there are plenty of ways to get break that reg exp. Commented Feb 18, 2020 at 19:55

3 Answers 3

0

Since JavaScript does not support the Singleline /s flag you will need to do a workaround for .:

/<script.*?>[\s\S]*?<\/script>/gi

https://regex101.com/r/7iFLnA/1

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

Comments

-1

Lazy loading should do the trick <script>(.+?)<\/script>

Comments

-1

try this regex

/<script.*?>.*?<\/script>/igm

https://stackoverflow.com/a/15816902/5812095

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.