removeScripts method

String removeScripts()

Removes <script> tags and JavaScript event handlers from the string.

This method uses regular expressions to remove script tags and attributes that may contain JavaScript event handlers (e.g., onclick, onload).

Example:

var htmlString = '<div onclick="alert(\'Hi\')">Content</div><script>alert("Hi");</script>';
var cleaned = htmlString.removeScripts();
print(cleaned); // Outputs: <div>Content</div>

Returns a string with script tags and JavaScript event handlers removed.

Implementation

String removeScripts() {
  final RegExp scriptTagRegExp =
      RegExp(r'<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>');
  final RegExp scriptAttrRegExp =
      RegExp(r'''\s+on\w+\s*=\s*["'][^"']*["']|\s+on\w+\s*=\s*[^\s>]+''');

  // Remove any script tags from the input
  var input = replaceAll(scriptTagRegExp, '');

  // Remove any event handler attributes (e.g. onmousedown, onclick) from all elements
  input = input.replaceAll(scriptAttrRegExp, '');

  return input;
}