Sometimes, we want to remove special symbols and extra spaces and replace with underscore using the replace method with JavaScript.
In this article, we’ll look at how to remove special symbols and extra spaces and replace with underscore using the replace method with JavaScript.
How to remove special symbols and extra spaces and replace with underscore using the replace method with JavaScript?
To remove special symbols and extra spaces and replace with underscore using the replace method with JavaScript, we call replace
with a regex.
For instance, we write
const newString = str.replace(/[^A-Z0-9]/gi, "_");
to call str.replace
with a regex that matches anything that aren’t alphanumeric characters.
The g
flag makes replace
replace all matches.
And i
makes replace
find matches in a case-insensitive manner.
We replace the matches with underscores.
Conclusion
To remove special symbols and extra spaces and replace with underscore using the replace method with JavaScript, we call replace
with a regex.