How to use Array Methods In Javascript
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.
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 }
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