3

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
But I'm curious how I can take a string, and search to see if any characters are uppercase, and if so, return true or return a string with the characters that are uppercase.

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.

DonnyyZ
  • 65
  • 1
  • 4

4 Answers4

11

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
Musa
  • 96,336
  • 17
  • 118
  • 137
3

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
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
punund
  • 4,321
  • 3
  • 34
  • 45
  • 1
    @CodyGray Your edit was misleading and unnecessary. This solution does not *"use a regular expression to filter out and return uppercase characters"*. – MikeM Jun 12 '22 at 14:29
0

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('');
}
smac89
  • 39,374
  • 15
  • 132
  • 179
-2

It's as simple as:

const hasUpperCase = str => /[A-Z]/.test(str);

console.log(hasUpperCase('abcd'));
console.log(hasUpperCase('abcD'));
MikeM
  • 13,156
  • 2
  • 34
  • 47
  • 3
    It doesn't work for `Ü` and such. – Arleigh Hix Jun 10 '22 at 23:30
  • 1
    Assuming that uppercase means A-Z is as wrong as using ASCII for storing arbitrary text. Here on Stack Overflow, I expect to read high-quality, general answers. Answers assuming that English is the only language in the world don't qualify for that. – Roland Illig Jun 12 '22 at 04:54