← Back to all snippets
JAVASCRIPT

Sanitize Input: Remove Special Characters

Learn to sanitize user input in JavaScript by removing all non-alphanumeric characters, making the text safe for display or further processing.

function sanitizeInput(input) {
  // Remove all characters that are NOT alphanumeric (a-z, A-Z, 0-9) or whitespace
  const sanitizedText = input.replace(/[^a-zA-Z0-9\s]/g, '');
  return sanitizedText;
}

// Usage:
console.log(sanitizeInput("Hello, World! This is a test. 123 @#$%"));
// Expected: "Hello World This is a test 123 "
console.log(sanitizeInput("User-Input with Punctuation."));
// Expected: "UserInput with Punctuation"
How it works: The `sanitizeInput` function cleans a string by removing unwanted special characters. It uses the regex `/[^a-zA-Z0-9\s]/g` to match any character that is NOT an uppercase letter, lowercase letter, digit, or whitespace character. The `replace()` method then substitutes these matched characters with an empty string, effectively removing them.

Need help integrating this into your project?

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

Hire DigitalCodeLabs