JAVASCRIPT

Sanitizing Input by Removing Non-Alphanumeric Characters

Clean user input by removing all characters that are not letters, numbers, or spaces, useful for basic text sanitization and data cleaning processes.

function sanitizeInput(inputString) {
  // Remove all non-alphanumeric characters except spaces
  // Note: For more robust security, consider specific libraries or context-aware sanitization.
  return inputString.replace(/[^a-zA-Z0-9\s]/g, '');
}

// Example usage:
console.log(sanitizeInput("Hello, World! 123@#$%^&*()")); // "Hello World 123"
console.log(sanitizeInput("   Extra spaces   and symbols!  ")); // "   Extra spaces   and symbols  "
console.log(sanitizeInput("Data_with_underscores-and-dashes")); // "Datawithunderscoresanddashes"
How it works: This JavaScript function provides a basic text sanitization method suitable for cleaning various user inputs. It employs a regular expression to replace all characters that are not alphanumeric (letters 'a-z', 'A-Z', numbers '0-9') or whitespace ('\s') with an empty string. This effectively removes special characters, leaving only letters, numbers, and spaces.

Need help integrating this into your project?

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

Hire DigitalCodeLabs