In this article, we’ll be looking at some ways to easily check if a string contains special characters in JavaScript.
1. RegExp test() Method
To check if a string contains special characters in JavaScript, we can test the string against a regular expression that matches any special character. We can use the RegExp
test()
method for this:
function containsSpecialChars(str) {
const specialChars =
/[`!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/;
return specialChars.test(str);
}
console.log(containsSpecialChars('book_club')); // true
console.log(containsSpecialChars('milk')); // false
console.log(containsSpecialChars('2 + 3 = 5')); // true
// Usage in if statement
if (containsSpecialChars('book_club')) {
console.log('Special characters found.');
} else {
console.log('No special characters found.');
}
The test()
method searches a string for a match with a regular expression. It returns true
if it finds a match, otherwise, it returns false
.
2. Array some() method
Another way to check if a string contains special characters is with the Array
some()
method:
function containsSpecialChars(str) {
const specialChars =
'[`!@#$%^&*()_+-=[]{};\':"\\|,.<>/?~]/';
return specialChars
.split('')
.some((specialChar) => str.includes(specialChar));
}
console.log(containsSpecialChars('book_club')); // true
console.log(containsSpecialChars('milk')); // false
console.log(containsSpecialChars('2 + 3 = 5')); // true
// Usage in if statement
if (containsSpecialChars('book_club')) {
console.log('Special characters found.');
} else {
console.log('No special characters found.');
}
First, we create a string containing all the special characters. Notice we have to use a backslash escape (\
) to include the single quote ('
) in the single-quoted string.
Then we call the String
split()
method, passing an empty string (''
) as an argument, to split the string into an array of all the special characters.
/** [
'[', '`', '!', '@', '#', '$', '%',
'^', '&', '*', '(', ')', '_', '+',
'-', '=', '[', ']', '{', '}', ';',
"'", ':', '"', '\\', '|', ',', '.',
'<', '>', '/', '?', '~', ']', '/'
] */
const specialChars =
'[`!@#$%^&*()_+-=[]{};\':"\\|,.<>/?~]/';
console.log(specialChars.split(''));
The Array
some()
method tests whether any element of an array satisfied a condition specified in the testing callback function. It returns true
if there is at least one element in the array that passes the test. Otherwise, it returns false
.
In our example, an element in the array of special characters only passes the test if the string contains the element. So, some()
returns true
if the string contains at least one special character.
Every Crazy Thing JavaScript Does
A captivating guide to the subtle caveats and lesser-known parts of JavaScript.