articles » current » javascript » remove-script-elements-from-html

JavaScript: Remove SCRIPT Elements from HTML

Use regular expressions to remove SCRIPT elements from HTML text.

This simple code will replace script tags and everthing contained between them with an empty string. The exception is when there is a string contained within the script tag that has the text </script> somewhere in it. This will break it, but some careful programming can overcome this.

Do this is .NET and C#.

Replace links in text with HTML Anchors.

var html = `<p>This is a test</p>

<script type='text/javascript'>

<p>The script tag should have been removed!</p>`;

var scriptRegex = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi;
var html2 = html.replace(scriptRegex, "");

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.