How to remove special characters from a string in JavaScript

Removing special characters from strings is crucial for data sanitization, URL slug generation, filename cleaning, and implementing features like username validation or search query normalization in JavaScript applications. With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented special character removal extensively in components like form validation, file upload systems, and search functionality where clean, standardized text improves data quality and user experience. From my extensive expertise, the most powerful and flexible solution is using the replace() method with regular expressions to target specific character patterns. This approach provides precise control over which characters to remove and handles complex filtering scenarios efficiently.

Use replace() with a regular expression to remove special characters from a string.

const text = 'Hello@#$% World!!!'
const cleaned = text.replace(/[^a-zA-Z0-9\s]/g, '')
// Result: 'Hello World'

The replace() method with the regular expression /[^a-zA-Z0-9\s]/g removes all characters that are not letters, numbers, or spaces. The ^ inside the brackets creates a negated character class, meaning it matches anything NOT in the specified range. The g flag makes it global, replacing all occurrences rather than just the first. In this example, all special characters like @, #, $, %, and ! are removed, leaving only ‘Hello World’. You can customize the regex pattern to keep specific characters like hyphens or underscores: /[^a-zA-Z0-9\s-_]/g.

Best Practice Note:

This is the same approach we use in CoreUI components for sanitizing user input, creating URL-friendly slugs, and processing form data throughout our component library. For keeping only alphanumeric characters, use /[^a-zA-Z0-9]/g. To remove only punctuation but keep accented characters, use /[^\w\s]/g. Consider what constitutes “special” for your use case and adjust the regex accordingly. Always test with international characters if your application supports multiple languages.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author