JAVASCRIPT
Sanitizing Script Tags from User Input
Prevent basic Cross-Site Scripting (XSS) by removing script tags and their content from user input using a JavaScript regular expression for initial sanitization.
function sanitizeScriptTags(inputString) {
// Regex to match <script>...</script> tags, including attributes and content
// It uses a non-greedy match for content and handles nested < > characters.
const scriptRegex = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi;
return inputString.replace(scriptRegex, '');
}
// Examples:
const maliciousInput = 'Hello <script>alert("XSS!");</script> World!';
console.log(sanitizeScriptTags(maliciousInput)); // 'Hello World!'
const anotherMalicious = 'Input with <script type="text/javascript">console.log("Malicious");</script> content.';
console.log(sanitizeScriptTags(anotherMalicious)); // 'Input with content.'
const safeInput = 'No script tags here.';
console.log(sanitizeScriptTags(safeInput)); // 'No script tags here.'
How it works: This JavaScript function `sanitizeScriptTags` employs a regular expression to remove `<script>` tags, along with all their attributes and content, from a given input string. The regex uses a non-greedy `*?` combined with a negative lookahead `(?!<\/script>)` to ensure it correctly matches the entire script block without stopping prematurely or overshooting. This provides a basic, client-side defense against some forms of Cross-Site Scripting (XSS) by cleaning user-submitted data.