JavaScript Program to Check if a String Contains any Special Character
Last Updated :
03 Jun, 2024
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
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.
JavaScript
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."
);
OutputGiven String is: Geeks$for$Geeks
String contains special characters
Using RegEx for Alphanumeric Characters
In this method, we will create a regex for all the alphanumeric numbers like A-Z,a-z, and 0-9. and test the string with the same.
Example: In this example, we will use regex.test method to test the given string.
JavaScript
const str = "Geeks$for$Geeks";
console.log("Given String is: " + str);
const regex = /[^A-Za-z0-9]/;
if (regex.test(str))
console.log(
"String contains special characters"
);
else
console.log(
"String does not contain any special character."
);
OutputGiven String is: Geeks$for$Geeks
String contains special characters
Using RegEx for Special Characters
In this method, we will create a regex for all the special characters mention above and test the string with the same..
Example: In this example, we will use regex.test method to test the given string.
JavaScript
const str = "GeeksforGeeks";
console.log("Given String is: " + str);
const regex = /[!@#$%^&*()\-+={}[\]:;"'<>,.?\/|\\]/;
if (regex.test(str))
console.log("String contains special characters");
else
console.log(
"String does not contain any special character."
);
OutputGiven String is: GeeksforGeeks
String does not contain any special character.
Using indexOf() method
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.
JavaScript
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."
);
}
OutputGiven string is : Geeks@forGeeks
String contain a special character.
Using the some Method
In this method, we will create an array of special characters and use the some method to check if any character in the given string is present in the array of special characters. The some method tests whether at least one element in the array passes the provided function.
Example: In this example, we will use the some method to check the given string.
JavaScript
function containsSpecialCharacter(str) {
const specialChars = ['!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '+', '=', '{', '}', '[', ']', ':', ';', '"', "'", '<', '>', ',', '.', '?', '/', '|', '\\'];
return str.split('').some(char => specialChars.includes(char));
}
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.");
}
OutputGiven string is: Geeks@forGeeks
String contains special characters.
Using the every Method
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.
JavaScript
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
OutputGiven string is: Geeks@forGeeks
String contains special characters.
Given string is: Geeks For Geeks
String does not contain any special character.
Similar Reads
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 '!', '@', '#', '$', '%', '^', '&', '
5 min read
JavaScript Program to Check Whether a String Starts and Ends With Certain Characters
In this article, We are going to learn how can we check whether a string starts and ends with certain characters. Given a string str and a set of characters, we need to find out whether the string str starts and ends with the given set of characters or not. Examples: Input: str = "abccba", sc = "a",
3 min read
JavaScript Program to Check if a Character is Vowel or Not
In this article, we will check if the input character is a vowel or not using JavaScript. Vowel characters are ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’. All other characters are not vowels. Examples: Input : 'u'Output : TrueExplanation: 'u' is among the vowel characters family (a,e,i,o,u).Input : 'b'Output : Fal
4 min read
JavaScript - String Contains Only Alphabetic Characters or Not
Here are several methods to check if a string contains only alphabetic characters in JavaScript Using Regular Expression (/^[A-Za-z]+$/) - Most USedThe most common approach is to use a regular expression to match only alphabetic characters (both uppercase and lowercase). [GFGTABS] JavaScript let s =
2 min read
JavaScript - Find if a Character is a Vowel or Consonant
Here are the different methods to find if a character is a vowel or consonant 1. Using Conditional Statements (If-Else)The most widely used approach is to check the character against vowels (both uppercase and lowercase) using conditional statements (if-else). This method is simple and effective for
5 min read
JavaScript Program to Validate String for Uppercase, Lowercase, Special Characters, and Numbers
In this article, we are going to learn how can we check if a string contains uppercase, lowercase, special characters, and numeric values. We have given string str of length N, the task is to check whether the given string contains uppercase alphabets, lowercase alphabets, special characters, and nu
4 min read
JavaScript Program to Find Uncommon Characters of the two Strings
In JavaScript, finding uncommon characters in two strings is the process of identifying the characters that exist in one string but not in the other string. We can find these uncommon characters using various approaches that are mentioned below: Table of Content Using SetsUsing Array.filter() method
2 min read
JavaScript Program to Check Whether the String is Symmetrical or Not
In this article, we will see how to check whether the given string is symmetric or not. The symmetrical string is one that is similar from the starting to mid and mid to end. Example: Input: khokhoOutput: The entered string is symmetricalInput: madamOutput: The entered string is not symmetricalInput
3 min read
JavaScript Program to Match Single Character with Multiple Possibilities
In this article, we will write programs to check all possible matching in JavaScript. We will check the occurrence of characters individually in the given string or sequence. In this article, we will check the occurrence of vowels in the given string. Table of Content Using JavaScript RegExp test()
3 min read
JavaScript - Compare Two Strings
These are the followings ways to compare two strings: 1. Using strict equality (===) operatorWe have defined a function that compare two strings using the strict equality operator (===), which checks if both the value and the type of the operands are equal. [GFGTABS] JavaScript let str1 = "hell
2 min read
JavaScript - Validate Password in JS
To validate a password in JavaScript regex to ensure it meets common requirements like length, uppercase letters, lowercase letters, numbers, and special characters. we will validate a strong or weak password with a custom-defined range. [GFGTABS] JavaScript let regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*
2 min read
PHP to Check if a String Contains any Special Character
Given a String, the task is to check whether a string contains any special characters in PHP. Special characters are characters that are not letters or numbers, such as punctuation marks, symbols, and whitespace characters. Examples: Input: str = "Hello@Geeks"Output: String contain special character
3 min read
How to check if a String contains a Specific Character in PHP ?
In PHP, determining whether a string contains a specific character is a common task. Whether you're validating user input, parsing data, or performing text processing, PHP provides several methods to check for the presence of a particular character within a string efficiently. Here are some common a
2 min read
PHP Program to Check if a String Contains Uppercase, Lowercase, Special Characters and Numeric Values
Given a String, the task is to check whether the given string contains uppercase, lowercase, special characters, and numeric values in PHP. When working with strings in PHP, it's often necessary to determine the presence of certain character types within the string, such as uppercase letters, lowerc
3 min read
Find Word Character in a String with JavaScript RegExp
Here are the different ways to find word characters in a string with JavaScript RegExp 1. Using \w to Find Word CharactersThe \w metacharacter in regular expressions matches any word character, which includes: A to Z (uppercase letters)a to z (lowercase letters)0 to 9 (digits)Underscore (_)You can u
3 min read
JavaScript - How To Check if String Contains Only Digits?
A string with only digits means it consists solely of numeric characters (0-9) and contains no other characters or symbols. Here are the different methods to check if the string contains only digits. 1. Using Regular Expression (RegExp) with test() MethodThe most efficient way to check if a string c
3 min read
Check if a Given String is Binary String or Not in JavaScript
Binary strings are sequences of characters containing only the digits 0 and 1. Other than that no number can be considered as Binary Number. We are going to check whether the given string is Binary or not by checking it's every character present in the string. Example: Input: "101010"Output: True, b
4 min read
How to Check a String Contains at least One Letter and One Number in PHP ?
This article will show you how to check if a string has at least one letter and one number in PHP. Validating whether a string contains at least one letter and one number is a common requirement. In this article, we will explore various approaches to achieve this task in PHP. Table of Content Using
3 min read
JavaScript Check if a string is a valid hex color representation
Given a hex color code and the task is to check whether the given hexCode is valid or not using JavaScript. We are going to discuss a few techniques. Approach: Valid hexcode contains the alphabets(A-F) and integers(0-9) and is of length 3 or 6.A RegExp is used to check whether the alphabets ranging
1 min read
How to check whether a passed string is palindrome or not in JavaScript?
We are given a string, our task is to find string is palindrome or not. A palindrome is a series of numbers, strings, or letters that, when read from right to left and left to right, match each other exactly or produce the same series of characters. in simple words when number strings or characters
4 min read