JAVASCRIPT

Sanitize Input to Alphanumeric and Safe Punctuation

Clean user input in JavaScript by removing all characters except alphanumeric, spaces, and common safe punctuation marks using a regular expression for security.

function sanitizeInput(inputString) {
  // Allows alphanumeric, spaces, and basic punctuation like .,!?'"- 
  const safeRegex = /[^a-zA-Z0-9 .,!?'"-]/g;
  return inputString.replace(safeRegex, '');
}

console.log(sanitizeInput("Hello, World! This is a test. <script>alert('xss')<\/script>"));
// Expected: "Hello, World! This is a test. alert'xss'"
console.log(sanitizeInput("[email protected] #Tag_123"));
// Expected: "UserEmail.com #Tag_123"
How it works: This JavaScript function sanitizes a given string by removing all characters that are not alphanumeric, spaces, or a predefined set of safe punctuation marks (period, comma, exclamation mark, question mark, apostrophe, double quotes, hyphen). This is useful for cleaning user input to prevent injection attacks or unwanted characters by whitelisting acceptable characters.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs