JAVASCRIPT

Sanitize String Input to Alphanumeric Characters

Clean user input by removing all non-alphanumeric characters, leaving only letters and numbers, using a simple JavaScript regular expression for data sanitization.

function sanitizeAlphanumeric(inputString) {
  return inputString.replace(/[^a-zA-Z0-9]/g, '');
}

// Example usage:
// const messyString = "Hello, World! 123 @#$%^&*";
// console.log(sanitizeAlphanumeric(messyString)); // "HelloWorld123"
How it works: This JavaScript function effectively cleans a given string by removing all characters that are not alphanumeric. The regular expression `/[^a-zA-Z0-9]/g` uses a negated character set (`[^...]`) to match any character that is NOT a lowercase letter, uppercase letter, or digit. The global flag (`g`) ensures that all such occurrences are replaced with an empty string, leaving only alphanumeric characters.

Need help integrating this into your project?

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

Hire DigitalCodeLabs