How to use indexOf() method In Javascript
In this approach we iterates over each character in the input string and For each character in the input string, the we checks if it exists in the specialChars string using indexOf() method, which returns the index of the character in the specialChars string. If the character is not found, indexOf() returns -1.
Example: In this example, we will use indexOf method to check the given string.
function containsSpecialCharacter(str) {
let specialChars =
"!@#$%^&*()-_=+[{]};:'\",<.>/?\\|";
for (var i = 0; i < str.length; i++) {
if (specialChars.indexOf(str[i]) !== -1) {
return true;
}
}
return false;
}
let str = "Geeks@forGeeks";
console.log("Given string is : "+ str)
if (containsSpecialCharacter(str)) {
console.log(
"String contain a special character."
);
} else {
console.log(
"String does not contain any special character."
);
}
Output
Given string is : Geeks@forGeeks String contain a 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
Contact Us