Check if String contains Special Characters in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

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 spaces to be special characters, add a space 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 beginning 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

We used the split method to split the string containing the special characters into an array.

Then we used the Array.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 iterates over the entire array.

We check if each special character is contained 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 a regular expression in this scenario. Both approaches are a bit hard to read, but the regex approach is a little more direct.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.