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: Beginner$For$Beginner
Output: String contains special characters
Explanation: Input string contain '$' symbol
Input: Beginner For Beginner
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

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 = "Beginner$for$Beginner";
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: Beginner$for$Beginner
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 = "Beginner$for$Beginner";
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: Beginner$for$Beginner
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 = "w3wiki";
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: w3wiki
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 = "Beginner@forBeginner";
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 : Beginner@forBeginner
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 = "Beginner@forBeginner";
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.");
    }

Output
Given string is: Beginner@forBeginner
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 = "Beginner@forBeginner";
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 = "Beginner For Beginner";
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: Beginner@forBeginner
String contains special characters.
Given string is: Beginner For Beginner
String does not contain any special character.


Contact Us