Naive Method – Using Loops
In this method, we will iterate the given string and check it for the ASCII values for the alphanumeric characters.
Example: In this example, we will use the for loop and check the ASCII value for every character.
let str = "Geeks$for$Geeks";
console.log("Given String is: " + str);
for (let i = 0; i < str.length; ++i) {
let ch = str.charCodeAt(i);
// console.log(ch);
if (
!(ch >= 65 && ch <= 90) && // A-Z
!(ch >= 97 && ch <= 122) && // a-z
!(ch >= 48 && ch <= 57) // 0-9
) {
return console.log(
"String contains special characters"
);
}
}
console.log(
"String does not contain any special character."
);
Output
Given String is: Geeks$for$Geeks String contains special characters
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
Contact Us