JAVASCRIPT
Sanitize String: Remove Special Characters
A JavaScript regex snippet to clean user input by removing all non-alphanumeric characters. Essential for data sanitization, security, and consistent formatting.
function sanitizeString(inputString) {
// Removes all characters that are not alphanumeric (a-z, A-Z, 0-9) or underscore.
// To allow spaces, you could use /[^a-zA-Z0-9_\s]/g
// To allow spaces and hyphens, use /[^a-zA-Z0-9_\s-]/g
return inputString.replace(/[^a-zA-Z0-9_]/g, '');
}
console.log(sanitizeString("Hello World! 123 @#$")); // HelloWorld123
console.log(sanitizeString("User_Name-1.0")); // User_Name10
console.log(sanitizeString(" leading and trailing spaces ")); // leadingandtrailingspaces
console.log(sanitizeString("My Title for a Blog Post?")); // MyTitleforBlogPost
How it works: This JavaScript function provides a simple yet effective way to sanitize strings by removing unwanted special characters. It uses a regular expression `/[^a-zA-Z0-9_]/g` to match any character that is NOT an alphanumeric character (a-z, A-Z, 0-9) or an underscore, and then replaces them with an empty string. This is particularly useful for cleaning user inputs like usernames, slugs, or tags to ensure data consistency and prevent potential issues.