How to use a Frequency Counter Object In Javascript
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.
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 }
JavaScript Program to Check if a String Contains Uppercase, Lowercase, Special Characters and Numeric Values
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 = "w3wiki@123"
Output : trueput: Yes
Explanation: The given string contains uppercase, lowercase,
special characters, and numeric values.
Input : str = “w3wiki”
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
Contact Us