I've read countless articles about people able to detect if all characters in a string are uppercase...
function isUpperCase(str) {
return str === str.toUpperCase();
}
isUpperCase("hello"); // false
isUpperCase("Hello"); // false
isUpperCase("HELLO"); // true
Any help is massively appreciated, I'm trying to avoid posts on here but I couldn't find an answer that worked for me anywhere else.
You can use the same logic you used for all uppercase, turn the string to lowercase and if its not equal to the original string it has an uppercase letter in it.
function hasUpperCase(str) {
return str !== str.toLowerCase();
}
console.log(hasUpperCase("hello")); // false
console.log(hasUpperCase("Hello")); // true
console.log(hasUpperCase("HELLO")); // true
You can use a regular expression to filter out and return uppercase characters. However, note that the naïve solution (as proposed by some of the other answers), /[A-Z]/, would detect only 26 uppercase Latin letters.
Here is a Unicode-aware regex solution:
const isAnyUpper = string => /\p{Lu}/u.test(string)
isAnyUpper('a') // false
isAnyUpper('A') // true
isAnyUpper('ф') // false
isAnyUpper('á') // false
isAnyUpper('Á') // true
Assuming the function is only taking string of ascii letters:
function isAllUpper(str) {
return str.split('').findIndex(ch => {
const code = ch.charCodeAt(0);
return code >= 65 && code <= 90;
}) === -1;
}
If you want to return just the string with only the uppercase letters, then you can extend the above slightly:
function onlyUpper(str) {
return str.split('').filter(ch => {
const code = ch.charCodeAt(0);
return code >= 65 && code <= 90;
}).join('');
}