Sometimes, we want to check for special characters in string with JavaScript.
In this article, we’ll look at how to check for special characters in string with JavaScript.
How to check for special characters in string with JavaScript?
To check for special characters in string with JavaScript, we can use the regex test
method.
For instance, we write
const format = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]+/;
const hasSpecialChars = format.test(string);
to define the format
regex that checks for the existence of any special characters listed in the square brackets.
Then we call format.test
with string
to check if string
has the characters listed in format
.
Conclusion
To check for special characters in string with JavaScript, we can use the regex test
method.