Wednesday, July 3, 2024
HomeLanguagesJavascriptJavaScript Program to Check if a String Contains 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.

All Methods to Check if the String Contains any Special Characters

  • Naive Method – Using Loops
  • Using RegularExpression for Alphanumeric Characters
  • Using RegEx for Special Characters

Approach 1: 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.")


Output

Given String is: Geeks$for$Geeks
String contains special characters

Approach 2: 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."
    );


Output

Given String is: Geeks$for$Geeks
String contains special characters

Approach 3: 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 = "neveropen";
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."
    );


Output

Given String is: neveropen
String does not contain any special character.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Nicole Veronica Rubhabha
Nicole Veronica Rubhabha
A highly competent and organized individual DotNet developer with a track record of architecting and developing web client-server applications. Recognized as a personable, dedicated performer who demonstrates innovation, communication, and teamwork to ensure quality and timely project completion. Expertise in C#, ASP.Net, MVC, LINQ, EF 6, Web Services, SQL Server, MySql, Web development,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments