← Back to all snippets
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.

Need help integrating this into your project?

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

Hire DigitalCodeLabs