Sometimes, we want to use string replace with regex to strip off illegal characters with JavaScript.
In this article, we’ll look at how to use string replace with regex to strip off illegal characters with JavaScript.
How to use string replace with regex to strip off illegal characters with JavaScript?
To use string replace with regex to strip off illegal characters with JavaScript, we define a regex that match all the characters we want to remove.
For instance, we write
const cleanString = dirtyString.replace(/[|&;$%@"<>()+,]/g, "");
to call dirtyString.replace
with a regex that matches anything in the square brackets.
The g
flag makes replace
replace all matches.
We replace each match with an empty string.
Conclusion
To use string replace with regex to strip off illegal characters with JavaScript, we define a regex that match all the characters we want to remove.