JAVASCRIPT

Sanitize Input: Remove Non-Alphanumeric Characters

Clean user input by removing all characters that are not letters or numbers, using a simple and effective JavaScript regex `replace` method.

function sanitizeAlphanumeric(input) {
  // Retains only letters (a-z, A-Z) and numbers (0-9).
  // The `g` flag ensures all occurrences are replaced, not just the first.
  return input.replace(/[^a-zA-Z0-9]/g, '');
}

// Usage:
console.log(sanitizeAlphanumeric('Hello! @World_123.')); // 'HelloWorld123'
console.log(sanitizeAlphanumeric('Special Chars: !@#$%^&*()')); // 'SpecialChars'
How it works: The `sanitizeAlphanumeric` function takes a string and returns a new string containing only alphanumeric characters. It achieves this by using the `replace()` method with a regular expression `/[^a-zA-Z0-9]/g`. The `[^...]` part is a negated character set, meaning it matches any character that is *not* a letter (a-z, A-Z) or a number (0-9). The `g` flag ensures that all non-alphanumeric characters throughout the string are replaced with an empty string.

Need help integrating this into your project?

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

Hire DigitalCodeLabs