How to use the every Method In Javascript
In this method, we will create a function that uses the every method to check if all characters in the string are alphanumeric or spaces. If every character is alphanumeric or a space, the string does not contain special characters; otherwise, it does.
Example: In this example, we will use the every method to check each character in the string.
function isAlphanumericOrSpace(char) {
return /^[a-zA-Z0-9 ]$/.test(char);
}
function containsSpecialCharacter(str) {
return !str.split('').every(isAlphanumericOrSpace);
}
let str = "Geeks@forGeeks";
console.log("Given string is: " + str);
if (containsSpecialCharacter(str)) {
console.log("String contains special characters.");
} else {
console.log("String does not contain any special character.");
}
str = "Geeks For Geeks";
console.log("Given string is: " + str);
if (containsSpecialCharacter(str)) {
console.log("String contains special characters.");
} else {
console.log("String does not contain any special character.");
}
// Nikunj Sonigara
Output
Given string is: Geeks@forGeeks String contains special characters. Given string is: Geeks For Geeks String does not contain any special character.
JavaScript Program to Check if a String Contains any Special Character
This article will demonstrate the methods to write a JavaScript Program to check if a String contains any special characters. Any string that contains any character other than alphanumeric and space includes the special character. These special characters are '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '+', '=', '{', '}', '[', ']', ':', ';', '"', '\'', '<', '>', ',', '.', '?', '/', '|', '\\',
etc.
Example:
Input: Geeks$For$Geeks
Output: String contains special characters
Explanation: Input string contain '$' symbol
Input: Geeks For Geeks
Output: String doesnot contain any special character.
Example of Checking if a String Contains any Special Character
Table of Content
- Naive Method – Using Loops
- Using RegEx for Alphanumeric Characters
- Using RegEx for Special Characters
- Using indexOf() method
- Using the some Method
- Using the every Method