0

I tried to remove the external script tag from a string using a regular expression.

var data = "<p>Valid paragraph.</p><p>Another valid paragraph.</p><script>alert123</script><script type='text/javascript' src='123'>Dangerous scripting!!!</script><script type='text/javascript' src='123'/><p>Last final paragraph.</p>";

data.replace(/<script[^>]\(\src=\)*>(?:(?!<\/script>)[^])*<\/script>/g, "")

output should be

"<p>Valid paragraph.</p><p>Another valid paragraph.</p><script>alert123</script><p>Last final paragraph.</p>";

but it not validating. how to fix this issue?

1
  • 3
    Regex is not the right tool to do such stuff. Use some xml parser to modify the XML DOM. Commented Feb 23, 2021 at 5:58

1 Answer 1

1

here I tested a regex and I think it is what you're looking for:

(<script[^>].*<\/script>)|(<script[^>].*\/\s?>)

https://regexr.com/5n377 see the effect!

EDIT

(<script[^>].*?<\/script>)|(<script[^>].*\/\s?>)
            ^^^ here Edited
Sign up to request clarification or add additional context in comments.

2 Comments

I fixed the issue. now it works fine @PatrickParker regexr.com/5n3ci
ok you fixed one problem with the reluctant qualifier. the other side of the regex still has the same problem with greedy qualifier. and there are countless ways it can fail. regex is the wrong approach here.

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.