Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript Program to Check if Two Strings are Same or Not
Next article icon

JavaScript Program to Validate String for Uppercase, Lowercase, Special Characters, and Numbers

Last Updated : 16 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 numeric values or not. If the string contains all of them, then returns “true”. Otherwise, return “false”.

Examples:

Input : str = "GeeksforGeeks@123"
Output : trueput: Yes
Explanation: The given string contains uppercase, lowercase,
special characters, and numeric values.
Input : str = “GeeksforGeeks”
Output : No
Explanation: The given string contains only uppercase
and lowercase characters.

Table of Content

  • Using Regular Expression
  • Using Array Methods
  • Using a Frequency Counter Object:
  • Using Array.prototype.every
  • Using Set to Check Character Categories

Using Regular Expression

We can use regular expressions to solve this problem. Create a regular expression to check if the given string contains uppercase, lowercase, special character, and numeric values as mentioned below:

Syntax:

regex = “^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)” + “(?=.*[-+_!@#$%^&*., ?]).+$” 

where,

  • ^ represents the starting of the string.
  • (?=.*[a-z]) represent at least one lowercase character.
  • (?=.*[A-Z]) represents at least one uppercase character.
  • (?=.*\\d) represents at least one numeric value.
  • (?=.*[-+_!@#$%^&*., ?]) represents at least one special character.
  • . represents any character except line break.
  • + represents one or more times.

Match the given string with the Regular Expression using Pattern.matcher(). Print True if the string matches with the given regular expression. Otherwise, print False.

Example:This example shows the use of the above-explained approach.

JavaScript
// JavaScript Program to Check if a string contains // uppercase, lowercase, special characters and // numeric values function isAllCharPresent(str) {     let pattern = new RegExp(         "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[-+_!@#$%^&*.,?]).+$"     );      if (pattern.test(str))         return true;     else         return false;     return; }  // Driver Code const str = "#GeeksForGeeks123@";  console.log(isAllCharPresent(str)); 

Output
true 

Using Array Methods

Convert the string to an array of characters. Utilize array methods like some() to check for uppercase, lowercase, special characters, and isNaN() to check for numeric values. Return the results in an object.

Example: In this example The function checkString analyzes a string for uppercase, lowercase, numeric, and special characters, returning an object indicating their presence. It's then tested with a sample string.

JavaScript
function checkString(str) {   const chars = Array.from(str);    const hasUppercase = chars.some(char => /[A-Z]/.test(char));   const hasLowercase = chars.some(char => /[a-z]/.test(char));   const hasNumeric = chars.some(char => !isNaN(char) && char !== ' ');   const hasSpecial = chars.some(char => /[!@#$%^&*(),.?":{}|<>]/.test(char));    return {     hasUppercase,     hasLowercase,     hasNumeric,     hasSpecial   }; }  const result = checkString("HelloWorld123!"); console.log(result); 

Output
{   hasUppercase: true,   hasLowercase: true,   hasNumeric: true,   hasSpecial: true } 

Using a Frequency Counter Object:

In this approach, we create an object to count the occurrences of each type of character (uppercase, lowercase, numeric, and special characters) in the string. Then, we check if each category has at least one occurrence.

JavaScript
function checkString(str) {   const charCount = {     uppercase: false,     lowercase: false,     numeric: false,     special: false   };    for (const char of str) {     if (/[A-Z]/.test(char)) {       charCount.uppercase = true;     } else if (/[a-z]/.test(char)) {       charCount.lowercase = true;     } else if (!isNaN(char) && char !== ' ') {       charCount.numeric = true;     } else if (/[!@#$%^&*(),.?":{}|<>]/.test(char)) {       charCount.special = true;     }   }    return charCount; }  const result = checkString("HelloWorld123!"); console.log(result); 

Output
{ uppercase: true, lowercase: true, numeric: true, special: true } 

Using Array.prototype.every

In this approach, we will create a function that uses the every method to check if all characters in the string meet certain criteria: uppercase, lowercase, numeric, and special characters.

Example: In this example, we will use the every method to check each character in the string.

JavaScript
function isAllCharPresent(str) {     const hasUppercase = [...str].some(char => /[A-Z]/.test(char));     const hasLowercase = [...str].some(char => /[a-z]/.test(char));     const hasNumeric = [...str].some(char => /\d/.test(char));     const hasSpecial = [...str].some(char => /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/.test(char));      return hasUppercase && hasLowercase && hasNumeric && hasSpecial; }  const str = "#GeeksForGeeks123@"; console.log(isAllCharPresent(str)); // Output: true  const str2 = "GeeksforGeeks"; console.log(isAllCharPresent(str2)); // Output: false // Nikunj Sonigara 

Output
true false 

Using Set to Check Character Categories

In this approach, we will use a Set to store the different types of characters found in the string. This way, we can easily check if the string contains at least one of each required character type.

Example: This example demonstrates how to use Set to check if a string contains uppercase, lowercase, numeric, and special characters.

JavaScript
function isAllCharPresent(str) {     const charTypes = new Set();     const specialCharacters = new Set(['!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '-', '=', '[', ']', '{', '}', ';', ':', '"', '\\', '|', ',', '.', '<', '>', '/', '?']);      for (const char of str) {         if (/[A-Z]/.test(char)) {             charTypes.add('uppercase');         } else if (/[a-z]/.test(char)) {             charTypes.add('lowercase');         } else if (/\d/.test(char)) {             charTypes.add('numeric');         } else if (specialCharacters.has(char)) {             charTypes.add('special');         }     }      return charTypes.has('uppercase') && charTypes.has('lowercase') && charTypes.has('numeric') && charTypes.has('special'); } const str1 = "#GeeksForGeeks123@"; console.log(isAllCharPresent(str1));  const str2 = "GeeksforGeeks"; console.log(isAllCharPresent(str2)); 

Output
true false 

Next Article
JavaScript Program to Check if Two Strings are Same or Not

B

blalverma92
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Geeks Premier League
  • javascript-string
  • JavaScript-Program
  • Geeks Premier League 2023

Similar Reads

  • JavaScript Program to Check if Two Strings are Same or Not
    In this article, we are going to implement a JavaScript program to check whether two strings are the same or not. If they are the same then we will return true else we will return false. Examples: Input: str1 = Geeks, str2 = GeeksOutput: True. Strings are the SameInput: str1 = Geeks, str2 = GeekOutp
    4 min read
  • JavaScript Program to Test if Kth Character is Digit in String
    Testing if the Kth character in a string is a digit in JavaScript involves checking the character at the specified index and determining if it is a numeric digit. Examples:Input : test_str = ‘geeks9geeks’, K = 5 Output : True Explanation : 5th idx element is 9, a digit, hence True.Input : test_str =
    5 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 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 - 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
  • JavaScript - Check if a String Contains Any Digit Characters
    Here are the various methods to check if a string contains any digital character 1. Using Regular Expressions (RegExp)The most efficient and popular way to check if a string contains digits is by using a regular expression. The pattern \d matches any digit (0-9), and with the test() method, we can e
    4 min read
  • How to Check Case of Letter in JavaScript ?
    There are different ways to check the case of the letters in JavaScript which are explained below comprehensively, one can choose the method that best suits their specific use case and requirement. Table of Content Using the function "toUpperCase()" or "toLowerCase"Using regular expressionUsing ASCI
    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
  • 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences