JAVASCRIPT

Sanitize Input: Allow Only Alphanumeric, Spaces, and Basic Punctuation

Clean user input by removing all characters except alphanumeric ones, spaces, and common punctuation marks using a simple JavaScript regex replacement.

function sanitizeInput(inputString) {
  // Allows letters (a-z, A-Z), numbers (0-9), spaces, and these specific symbols: -_.!?,()
  const sanitized = inputString.replace(/[^a-zA-Z0-9\s\-_\.!?,()]/g, '');
  return sanitized;
}

// Example usage:
const unsafeInput = "Hello, world! This is a test with some $ymb0ls and <script>tags</script>.";
const safeInput = sanitizeInput(unsafeInput);
console.log(safeInput); // "Hello, world! This is a test with some ymb0ls and tags."
How it works: This JavaScript function `sanitizeInput` takes a string and removes unwanted characters, leaving only alphanumeric characters, spaces, and a predefined set of punctuation marks (`-_.!?,()`). The regular expression `/[^a-zA-Z0-9\s\-_\.!?,()]/g` matches any character that is NOT in the allowed set (`[^...]`). The `replace` method with the global flag `g` then replaces all such disallowed 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