JAVASCRIPT
Sanitize String for Alphanumeric, Spaces, and Hyphens
Clean user input or text content by removing unwanted characters, allowing only letters, numbers, spaces, and hyphens using a concise JavaScript Regex pattern.
function sanitizeInput(inputString) {
// Allows alphanumeric characters (a-z, A-Z, 0-9), spaces (\s), and hyphens (-)
// Replaces any character NOT in this set with an empty string.
return inputString.replace(/[^a-zA-Z0-9\s-]/g, '');
}
const dirtyString = "Hello World! This is a test string with $pecial Ch@racters and some_underscores.";
const cleanString = sanitizeInput(dirtyString);
console.log(cleanString);
// Expected Output: Hello World This is a test string with pecial Chracters and someunderscores
How it works: This JavaScript function uses `String.prototype.replace()` with a regular expression to sanitize an input string. The regex `[^a-zA-Z0-9\s-]` matches any character that is *not* an uppercase letter, lowercase letter, digit, whitespace character, or hyphen. The `g` flag ensures all occurrences are replaced, effectively cleaning the string of unwanted symbols.