Borislav Hadzhiev
Thu Oct 21 2021·2 min read
Photo by Meg Wagener
To check if a string contains special characters, call the test()
method on
a regular expression that matches any special character. The test
method will
return true
if the string contains at least 1 special character and false
otherwise.
function containsSpecialChars(str) { const specialChars = /[`!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/; return specialChars.test(str); } console.log(containsSpecialChars('hello!')); // 👉️ true console.log(containsSpecialChars('abc')); // 👉️ false console.log(containsSpecialChars('one two')); // 👉️ false if (containsSpecialChars('hello!')) { console.log('✅ string contains special characters'); } else { console.log('⛔️ string does NOT contain special characters'); }
space
to be a special character, add it between the square brackets []
.// 👇️ with space as special character // 👇️ const specialChars = /[ `!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/;
We used the RegExp.test method to check if a string contains special characters.
The method returns true
if the regular expression is matched in the string and
false
otherwise.
The forward slashes / /
mark the start and end of the regular expression.
The square brackets []
are called a character class and match any of the
characters between the brackets.
If you're not a big fan of regular expression, you could use the some
method
instead.
function containsSpecialChars(str) { const specialChars = `\`!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~`; const result = specialChars.split('').some(specialChar => { if (str.includes(specialChar)) { return true; } return false; }); return result; } console.log(containsSpecialChars('hello')); // 👉️ false console.log(containsSpecialChars('hello!')); // 👉️ true
In this code snippet, we use the split
method to split the string containing
the special characters into an array.
Then we use the some
method to iterate over the array.
some
method gets called with each array element (special character) until it returns a truthy value or it iterates over the entire array.We check if each special character is included in the string. If the string
contains at least 1 special character, we return true
and the some
method
short-circuits.