Check if String contains Special Characters in JavaScript

avatar

Borislav Hadzhiev

Thu Oct 21 20212 min read

banner

Photo by Meg Wagener

Check if String contains Special Characters #

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.

index.js
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'); }
If you consider space to be a special character, add it between the square brackets [].
index.js
// ๐Ÿ‘‡๏ธ 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 don't consider any of the characters between the brackets a special character, remove them.

If you're not a big fan of regular expression, you could use the some method instead.

index.js
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.

The function we passed to the 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.

My personal preference is to use the regular expression in this scenario, because both approaches are a bit hard to read, but the regex approach is a bit more direct.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee