463

How can I test if a letter in a string is uppercase or lowercase using JavaScript?

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
Joe
  • 5,341
  • 3
  • 19
  • 14
  • 3
    can i just clarify the question - you want to test if a particular letter in a string is upper or lower - or do you want to test if the whole string contains any letter that is uppercase or lowercase. if it is the latter then how do you propose getting the result without looping through the string and testing one letter at a time? – Josh Jun 22 '09 at 14:02
  • 3
    http://jsperf.com/isupper-comparison/5 A few ideas there, and you can test them for speed as well. – odinho - Velmont Jan 16 '12 at 18:41
  • 2
    Idea #4 (`[:upper:]`) is fast and very cool except that it doesn't work, see [my comment](http://stackoverflow.com/a/1718290/237105) below and my corrected http://jsperf.com/isupper-comparison/7. – Antony Hatchkins Jun 12 '13 at 12:34
  • 9
    `str == str.toUpperCase();` returns **true** or **false** – Jacksonkr Sep 20 '17 at 13:52
  • 2
    `str.toUpperCase() === str && str.toLowerCase() !== str`, if you really don't want to use regExp. – Alireza Mirian Apr 17 '21 at 11:59

31 Answers31

489

The answer by josh and maleki will return true on both upper and lower case if the character or the whole string is numeric. making the result a false result. example using josh

var character = '5';
if (character == character.toUpperCase()) {
 alert ('upper case true');
}
if (character == character.toLowerCase()){
 alert ('lower case true');
}

another way is to test it first if it is numeric, else test it if upper or lower case example

var strings = 'this iS a TeSt 523 Now!';
var i=0;
var character='';
while (i <= strings.length){
    character = strings.charAt(i);
    if (!isNaN(character * 1)){
        alert('character is numeric');
    }else{
        if (character == character.toUpperCase()) {
            alert ('upper case true');
        }
        if (character == character.toLowerCase()){
            alert ('lower case true');
        }
    }
    i++;
}
Lewis Cianci
  • 926
  • 1
  • 13
  • 38
  • 30
    Won't you still have the same false result if the character is something neither numeric nor alpha, such as punctuation? – LarsH Jun 10 '11 at 14:25
  • 6
    @LarsH see this: http://stackoverflow.com/questions/1027224/how-can-i-test-if-a-letter-in-a-string-is-uppercase-or-lowercase-using-javascrip/9728437#answer-9728437 – ciembor Mar 15 '12 at 21:32
  • 1
    This code will alert that punctuation characters like `!` are numeric. – Barmar May 23 '14 at 04:16
  • 1
    Why not check both whether the char equals its own lowercase and uppercase, if both are true, then false. –  Oct 10 '17 at 00:01
  • Uncaught SyntaxError: Unexpected token ; at line 4 `while (i <= strings.length){` this line has some gibberish – giorgio79 Nov 24 '17 at 08:53
  • P.S. Anything involving the ASCII table is inherently wrong as well. Because there are a lot of characters in Unicode that belong to the upper and lower case groups. There's lots of languages out there. – Sonic Beard Apr 08 '18 at 22:37
  • Anything implemented on this logic would treat non-alphanumeric characters as having both upper and lower case by returning true for either case. These other characters are actually without case. The following code provides a more precise result. This allows a binary answer to be derived as the author requested with the additional advantage of distinguishing characters without case. `var caseGroup = (character.toLowerCase() == character.toUpperCase() ? 0 : (character == character.toUpperCase() ? 1 : -1));` – Sonic Beard Apr 08 '18 at 22:46
  • correct detection of UpperCase for letters `if (isNaN(char * 1) && char === char.toLowerCase() && char !== char.toUpperCase()) { alert('letter is UpperCase'); }` – Cyclion Aug 08 '19 at 04:04
  • what could I do if I just want to validate the lowercase but also I want check if there are more than x number of lowercases? – Pxaml Jul 03 '21 at 22:32
  • `const isUpper = c => c !== c.toLowerCase();` – Justin Nov 17 '21 at 18:20
  • The specification mandates that the input be a letter: “How can I test if a letter in a string is uppercase or lowercase”. Undefined behaviour in any other case is expected. – Philippe-André Lorin Jan 15 '22 at 12:16
  • meanwhile for loop – danik0011 Jul 07 '23 at 17:51
91

The problem with the other answers is, that some characters like numbers or punctuation also return true when checked for lowercase/uppercase.

I found this to work very well for it, e.g. "3" will now return false ("3" is lowerCase by default) however consider to filter out numbers with isNaN() and make sure it's actually a string you're testing. Here the code:

function isLowerCase(str) {
    return str === str.toLowerCase() &&
           str !== str.toUpperCase();
}

This will work for punctuation, numbers and letters:

assert(isLowerCase("a"))
assert(!isLowerCase("Ü"))
assert(!isLowerCase("4"))
assert(!isLowerCase("_"))

To check one letter just call it using isLowerCase(str[charIndex])

faebster
  • 727
  • 7
  • 13
WebFreak001
  • 2,415
  • 1
  • 15
  • 24
  • 7
    Don't know why the other answers are voted. This is the only solution I could think of as well - the logic being "does the character have upper && lower case variants? If so then return whether it's upper or lower case" – aaaaaa Sep 09 '16 at 14:31
  • Sorry but this seems to be a duplicate of another [three year old answer](https://stackoverflow.com/a/9728437). – Gaurang Tandon Jun 09 '18 at 06:35
  • 4
    @GaurangTandon yeah 2 years after answering I noticed that too, but I didn't notice before because it is wrapped in a for loop, logging something to console and in general not a reusable code snippet so I and (based on the votes on this answer) many other people naturally just skipped the answer. Therefore I think it's good to have this as quick copy-paste answer as opposed to the other answer. – WebFreak001 Jun 10 '18 at 10:24
  • Convert the entire string just in order to check the ASCII value of one character? Wasteful. – Engineer Aug 16 '19 at 14:31
  • function isLowerCase(str) { return str == str.toLowerCase() } – latitov May 04 '21 at 17:57
  • I don't understand why you check for != upperCase, what you are checking LITERALLY Should be whether the character, once converted to lowercase remains the same, the character converted to uppercase being different is none of your business IMO. if you ask me if '3' is lowercase I would say 'yes', and if you ask me if ';' is lowercase I would say yes your function would fail on the second if clause '3'.toUpper != '3 ==> false – E.Serra Dec 22 '21 at 11:33
  • @E.Serra I would argue '3' and ';' are not lowercase, because there are no uppercase variants. This is also the same how other common APIs work. (Java's Character.isLowerCase for example) Unicode also has character categories like uppercase letters and lowercase letters, where non-letters are not included. – WebFreak001 Dec 22 '21 at 12:10
  • it depends on situation. If you e.g. analyse a FEN (chess position notation) and check for numbers first, then only characters will be input, where `str === str.toLowerCase()` is enough, but if you have numbers and punctuation in the string, `.toLowerCase()` or the upper version are maybe too early anyway and you should first make sure, you check for a character-only string. A good habit is to use `===` three equals to compare, to avoid JS surprises, or reading seven books about that topic ;) it's always active in my linter. – faebster Jun 12 '23 at 15:00
  • @E.Serra to answer your concern: The question is not specific enough to say other answers are wrong. a letter in a string (if containing only characters) can surely be compared by `str === str.toLowerCase()` nobody said anything about punctuation or numbers and special signs in the string ;) That's way it's always a great idea to put a sample or a anonymized equivalent when writing a question. While going for the bullet proof variation is great, what if you need the smallest code portion for your project, because you're e.g. on a TV box with limitations.. we just can assume here... – faebster Jun 12 '23 at 15:02
86
if (character == character.toLowerCase())
{
  // The character is lowercase
}
else
{
  // The character is uppercase
}
Daniel Vandersluis
  • 91,582
  • 23
  • 169
  • 153
69
const isUpperCase = (string) => /^[A-Z]*$/.test(string)

then :

isUpperCase('A') // true
isUpperCase('a') // false
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
  • 5
    best answer by far, fast, not allocating any memory, or transforming data. – Martijn Scheffer Sep 06 '18 at 22:19
  • 7
    Not working with accented characters (á, Á), vowel mutations (öÖ, äÄ, üÜ) and graphemes (ß,ẞ) tho. – NullDev Aug 16 '20 at 14:57
  • Are you sure this is Go, and not JS? – latitov May 04 '21 at 17:59
  • 2
    @latitov what do you mean? This is plain JavaScript. – Shadow The GPT Wizard Jun 17 '21 at 07:58
  • @MartijnScheffer We actually do not know whether this answer is faster than converting to uppercase and comparing, nor do we even know that we do not allocate any memory. It's pretty much guaranteed that the regular expression will parse the string and allocate a bunch of nodes for the regular expression handling. I think it is also likely that creating the regex parser has more overhead that converting to uppercase, particularly in the one-character string case (but of course without testing we do not know). – prewett Aug 29 '23 at 00:00
  • when you convert the case, it will create a new string, yes we know when memory is allocated ! the regular expression will only be created once, how do i know ? i wrote JS compilers, i read most of Spidermoney, and V8, frankly your answer sounds a bit arbitrary, there is no testing needed if you understand how JS engines work allocating memory is a lot more costly than some maths, and regular expressions are highly optimised. if i really needed the best performance i would use a table (a Map in JS) – Martijn Scheffer Aug 30 '23 at 01:06
50

This will log true if character is uppercase letter, and log false in every other case:

var letters = ['a', 'b', 'c', 'A', 'B', 'C', '(', ')', '+', '-', '~', '*'];

​​​for (var ​i = 0; i<letters.length; i++) {
    if (letters[i] === letters[i].toUpperCase()
        && letters[i] !== letters[i].toLowerCase()) {
        console.log(letters[i] + ": " + true);
    } else {
        console.log(letters[i] + ": " + false);
    }
}​

You may test it here: http://jsfiddle.net/Axfxz/ (use Firebug or sth).

​​​for (var ​i = 0; i<letters.length; i++) {
    if (letters[i] !== letters[i].toUpperCase()
        && letters[i] === letters[i].toLowerCase()) {
        console.log(letters[i] + ": " + true);
    } else {
        console.log(letters[i] + ": " + false);
    }
}​

and this is for lowercase:).

ciembor
  • 7,189
  • 13
  • 59
  • 100
  • 1
    BTW, also works with accented characters like "É", "Ñ", and "ñ". – Xavi Nov 17 '13 at 17:25
  • 6
    Unfortunately, there are lowercase letters that don't have an uppercase variant (and probably the other way around as well). The German 'ß' is a lowercase letter, but if you apply the second function on it, it will result in a false. – jplatte Aug 05 '15 at 19:22
  • 2
    Okay, try this: `შეარჩიე კატეგორიების მიხედვით` – vovchisko Nov 21 '20 at 21:18
25
function isUpperCase(myString) { 
  return (myString == myString.toUpperCase()); 
} 
function isLowerCase(myString) { 
  return (myString == myString.toLowerCase()); 
} 
Josh
  • 6,256
  • 2
  • 37
  • 56
  • 1
    i believe this solution only works if the string is one character long and that character is the character of interest...you'd need to get the character first before calling either of these methods – zaczap Jun 22 '09 at 13:41
  • 4
    @zaczap - incorrect. These will transform (and then test) the entire string. – scunliffe Jun 22 '09 at 13:42
  • 3
    +1 to the comments - this answer is slightly off, in respect to the original question, which asked about a letter in a string (Not the whole string) – belugabob Jun 22 '09 at 13:47
  • 2
    Let's not forget strict equality checking! === FTW! – James Jun 22 '09 at 13:49
  • 1
    @all - correct it will only test against a whole string - you could loop through the letters within a string to test each one. – Josh Jun 22 '09 at 13:52
  • You could loop and check each - but that wasn't the question -- :) – hugoware Jun 22 '09 at 13:53
  • This is the best solution because it supports non-English uppercase characters. For example, uppercase of Polish UTF-8 character "ą" is "Ą". – kravietz Apr 01 '15 at 12:19
25

You could utilize a regular expression test and the toUpperCase method:

String.prototype.charAtIsUpper = function (atpos){
      var chr = this.charAt(atpos);
      return /[A-Z]|[\u0080-\u024F]/.test(chr) && chr === chr.toUpperCase();
};
// usage (note: character position is zero based)
'hi There'.charAtIsUpper(3);      //=> true
'BLUE CURAÇAO'.charAtIsUpper(9);  //=> true
'Hello, World!'.charAtIsUpper(5); //=> false

See also

KooiInc
  • 119,216
  • 31
  • 141
  • 177
18
function isCapital(ch){
    return ch.charCodeAt() >= 65 && ch.charCodeAt() <= 90;
}
Arthur van Acker
  • 472
  • 7
  • 10
10

More specifically to what is being asked. Pass in a String and a position to check. Very close to Josh's except that this one will compare a larger string. Would have added as a comment but I don't have that ability yet.

function isUpperCase(myString, pos) { 
    return (myString.charAt(pos) == myString.charAt(pos).toUpperCase()); 
}   

function isLowerCase(myString, pos) {
    return (myString.charAt(pos) == myString.charAt(pos).toLowerCase()); 
}
Luboš Turek
  • 6,273
  • 9
  • 40
  • 50
Maleki
  • 1,486
  • 1
  • 17
  • 26
8

A good answer to this question should be succinct, handle unicode correctly, and deal with empty strings and nulls.

function isUpperCase(c) {
    return !!c && c != c.toLocaleLowerCase();
}

This approach deals with empty strings and nulls first, then ensures that converting the given string to lower case changes its equality. This ensures that the string contains at least one capital letter according to the current local's capitalisation rules (and won't return false positives for numbers and other glyphs that don't have capitalisation).

The original question asked specifically about testing the first character. In order to keep your code simple and clear I'd split the first character off the string separately from testing whether it's upper case.

Stephen Nelson
  • 939
  • 1
  • 7
  • 22
7

You can also use a regular expression to explicitly detect uppercase roman alphabetical characters.

isUpperCase = function(char) {
  return !!/[A-Z]/.exec(char[0]);
};

EDIT: the above function is correct for ASCII/Basic Latin Unicode, which is probably all you'll ever care about. The following version also support Latin-1 Supplement and Greek and Coptic Unicode blocks... In case you needed that for some reason.

isUpperCase = function(char) {
  return !!/[A-ZÀ-ÖØ-ÞΆΈ-ΏΑ-ΫϢϤϦϨϪϬϮϴϷϹϺϽ-Ͽ]/.exec(char[0]);
};

This strategy starts to fall down if you need further support (is Ѭ uppercase?) since some blocks intermix upper and lowercase characters.

Nat
  • 2,689
  • 2
  • 29
  • 35
  • @RobertReiz Really? This doesn't work for non-Roman characters. – Barmar May 23 '14 at 04:14
  • This is missing tons of other locale characters, for example Polish. For this reason the solution that uses comparison against `.toLowerCase()` or `.toUpperCase()` are preferred, as they support most of the locales internally. – kravietz Apr 01 '15 at 12:21
  • 1
    “Which is probably all you'll ever care about”. No. Many people do, and many others should, care about languages other than contemporary English. Hard-coding the few characters you happen to care about at the time you’re writing the function is bad practice. Also, yes, Ѭ is uppercase (ѭ being the lowercase variant). – Philippe-André Lorin Jan 15 '22 at 12:23
  • 1
    Why the more expensive `exec` followed by double-negation to force to `true`/`false` when you could just use the cheaper `test` and get `true`/`false` directly? `return /[A-Z]/.test(char[0]);` Pretty sure support for `test` is just as old as `exec`, so it should work on any browser `exec` works on (which is basically every browser AFAICT). – ShadowRanger Apr 07 '23 at 16:52
7

There's a really simple answer, which nobody else has mentioned:

function isLowerCase(str) {
    return str !== str.toUpperCase();
}

If str.toUpperCase() does not return the same str, it has to be lower case. To test for upper case you change it to str !== str.toLowererCase().

Unlike some other answers, it works correctly on non-alpha characters (returns false) and it works for other alphabets, accented characters etc.

James
  • 5,635
  • 2
  • 33
  • 44
  • I was about to brag about this discovery, but you were first. It's useful to detect if the first character is uppercase and a letter at once – Pawel Apr 27 '17 at 04:04
  • Prefer Arthur van Acker's answer: there is no need to waste CPU by _converting_ the entire string to uppercase, just to _check_ whether _one character_ is upper case. You can simply do an ASCII range check on that character. Conversion works, sure, but it's lazy coding. – Engineer Aug 16 '19 at 14:29
  • @Engineer, but Acker's answer is wrong `"É"` is not lower case. – James Aug 19 '19 at 10:29
7

With modern browsers you can use regexp and unicode property tests e.g.

/\p{Lu}/u.test("A") // is true
/\p{Lu}/u.test("Å") // is true
/\p{Lu}/u.test("a1å") // is false

More info here:

List of general categories here:

Jens
  • 2,327
  • 25
  • 34
5

This is straightforward, readable solution using a simple regex.

// Get specific char in string
const char = string.charAt(index);

const isLowerCaseLetter = (/[a-z]/.test(char));
const isUpperCaseLetter = (/[A-Z]/.test(char));
Gibolt
  • 42,564
  • 15
  • 187
  • 127
5

I believe this is the easiest solution.. You can use onchange handler in input field .. to do the validation

const isValid = e.target.value === e.target.value.toLowerCase()

if (isValid) {
  //Do something
} else {
  //Do something
}
4

You can also use this, it will check the string for lower and uppercase

var s = "a"
if(/[a-z]/.test(s)){
  alert ('lower case true');
}

if(/[A-Z]/.test(s)) {
 alert ('upper case true'); 
}
Himanshu Teotia
  • 2,126
  • 1
  • 27
  • 38
4

The best way is to use a regular expression, a ternary operator, and the built in .test() method for strings.

I leave you to Google the ins and outs of regular expressions and the test method for strings (they're easy to find), but here we'll use it to test your variable.

/[a-z]/i.test(your-character-here)

This will return TRUE of FALSE based on whether or not your character matches the character set in the regular expression. Our regular expression checks for all letters a-z /[a-z]/ regardless of their case thanks to the i flag.

So, a basic test would be:

var theAnswer = "";
if (/[a-z]/i.test(your-character-here)) {
  theAnswer = "It's a letter."
}

Now we need to determine if it's upper or lower case. So, if we remove the i flag from our regular expression, then our code above will test for lower case letters a-z. And if we stick another if statement in the else of our first if statement, we can test for upper case too by using A-Z. Like this:

var theAnswer = "";
if (/[a-z]/.test(your-character-here)) {
  theAnswer = "It's a lower case letter."
} else if (/[A-Z]/.test(your-character-here)) {
  theAnswer = "It's an upper case letter.";
}

And just in case it's not a letter, we can add a final else statement:

var theAnswer = "";
if (/[a-z]/.test(your-character-here)) {
  theAnswer = "It's a lower case letter."
} else if (/[A-Z]/.test(your-character-here)) {
  theAnswer = "It's an upper case letter.";
} else {
  theAnswer = "It's not a letter."
}

The above code would work. But it's kinda ugly. Instead, we can use a "ternary operator" to replace our if-else statements above. Ternary operators are just shorthand simple ways of coding an if-else. The syntax is easy:

(statement-to-be-evaluated) ? (code-if-true) : (code-if-false)

And these can be nested within each other, too. So a function might look like:

var theAnswer = "";
function whichCase(theLetter) {
  theAnswer = /[a-z]/.test(theLetter) ? "It's lower case." : "";
  theAnswer = /[A-Z]/.test(theLetter) ? "It's upper case." : "";
  return(theAnswer);
}

The above code looks good, but won't quite work, because if our character is lower case, theAnswer gets set to "" when it test for uppercase, so lets nest them:

var theAnswer = "";
function whichCase(theLetter) {
  theAnswer = /[a-z]/.test(theLetter) ? "It's lower case." : (/[A-Z]/.test(theLetter) ? "It's upper case." : "It's not a letter.");
  return(theAnswer);
}

That will work great! But there's no need to have two seperate lines for setting the variable theAnswer and then returning it. And we should be using let and const rather than var (look those up if you're not sure why). Once we make those changes:

function whichCase(theLetter) {
  return(/[A-Z]/.test(theLetter) ? "It's upper case." : (/[a-z]/.test(theLetter) ? "It's lower case." : "It's not a letter.")); 
}

And we end up with an elegant, concise piece of code. ;)

4

See my comment on the chosen answer. Other solutions that limit to the ASCII table or use the actual character literals completely ignore Unicode and the several hundred other characters there that have case.

This code will set the caseGroup variable to:

  • 1 for Upper Case
  • -1 for Lower Case
  • 0 for Without Case

    var caseGroup = (character.toLowerCase() == character.toUpperCase() ? 0 : (character == character.toUpperCase() ? 1 : -1));
    

You could bake that into something like this...

    function determineCase(character) {
        return (character.toLowerCase() == character.toUpperCase() ? 0 : (character == character.toUpperCase() ? 1 : -1));
    }

    function isUpper(character) {
        return determineCase(character) == 1;
    }

    function isLower(character) {
        return determineCase(character) == -1;
    }

    function hasCase(character) {
        return determineCase(character) != 0;
    }
Sonic Beard
  • 505
  • 4
  • 6
3
function solution(s) {
var c = s[0];

if (c == c.toUpperCase() && !(c >= '0' && c <= '9') &&(c >='A' && c <= 'Z')) {
    return 'upper';
} else if (c == c.toLowerCase() && !(c >= '0' && c <= '9') &&(c >='a' && c <= 'z')){
    return 'lower';
} else if (c >= '0' && c <= '9'){
   return 'digit'
} else {
  return 'other' 
}
}

var str1= (solution('A')) // upper
var str2 = solution('b') // lower
var str3 = solution('1') // digit
var str4 = solution('_') // other
console.log(`${str1} ${str2} ${str3} ${str4}`)
Huy Do
  • 49
  • 5
2

You can test if your array has an upper case or lower case string by using the match method and regex, below is just a basic foundation to start your test

  var array = ['a', 'b', 'c', 'A', 'B', 'C', '(', ')', '+', '-', '~', '*'];
  var character = array.join('')
      console.log(character)

  var test = function(search){
      upperCase = search.match(/[A-Z]/g)
      console.log(upperCase)

      lowerCase = search.match(/[a-z]/g)
      console.log(lowerCase)
   }

   test(character)
user3449311
  • 205
  • 2
  • 5
2

This is how I did it recently:

1) Check that a char/string s is lowercase

s.toLowerCase() == s && s.toUpperCase() != s

2) Check s is uppercase

s.toUpperCase() == s && s.toLowerCase() != s

Covers cases where s contains non-alphabetic chars and diacritics.

2
function checkCharType (charToCheck) {
    // body... 
    var returnValue = "O";
    var charCode = charToCheck.charCodeAt(0);

    if(charCode >= "A".charCodeAt(0) && charCode <= "Z".charCodeAt(0)){

        returnValue = "U";

    }else if (charCode >= "a".charCodeAt(0) &&
                charCode <= "z".charCodeAt(0) ){
        returnValue = "L";
    }else if (charCode >= "0".charCodeAt(0) &&
            charCode <= "9".charCodeAt(0)  ) {
        returnValue = "N";
    }
    return returnValue;
}

var myString = prompt("Enter Some text: ", "Hello world !");

switch (checkCharType(myString)) {
    case "U":
        // statements_1
        document.write("First character was upper case");
        break;

    case "L":
        document.write("First character was a lower case");
        break;
    case "N":
        document.write("First character was a number");
        break
    default:
        // statements_def
        document.write("First character was not a character or a number");
        break;
}
  1. Define a Function checkCharType().By declaring the variable returnValue and initialising it to the Character "O" to indicate it's Some other value.

  2. U for uppercase; L for Lowercase ; N for number

  3. Use the charCodeAt() method to get the character code of the first character.

  4. Using if Statement , which check within what range of values the character code falls.

  5. If it falls between the character codes for A and Z, Its Uppercase, character code between a and z ,Its Lowercase. and so on.

  6. "A".charCode(0)

    var myChar = new String("A"); myChar.charCodeAt(0); "A" : number code "65“

  7. Check the String
Fenici
  • 461
  • 1
  • 5
  • 19
2

This checks the ENTIRE string, not just the first letter. I thought I'd share it with everyone here.

Here is a function that uses a regular expression to test against the letters of a string; it returns true if the letter is uppercase (A-Z). We then reduce the true/false array to a single value. If it is equal to the length of the string, that means all the letters passed the regex test, which means the string is uppercase. If not, the string is lowercase.

const isUpperCase = (str) => {
  let result = str
    .split('')
    .map(letter => /[A-Z]/.test(letter))
    .reduce((a, b) => a + b);

  return result === str.length;
}

console.log(isUpperCase('123')); // false
console.log('123' === '123'.toUpperCase()); // true
Matthew
  • 2,158
  • 7
  • 30
  • 52
2

This question has clearly been answered a number of times, but i thought i'd share my solution as I haven't seen it in the given answers.

var lower_case = function(letter){
    lowers = "abcdefghijklmnopqrstuvwxyz";
    return letter === letter.toLowerCase() && lowers.indexOf(letter) >= 0
};

var upper_case = function(letter){
    uppers = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    return letter === letter.toUpperCase() && uppers.indexOf(letter) >= 0
};

jstm
  • 420
  • 4
  • 14
2
function checkCase(c){
    var u = c.toUpperCase();
    return (c.toLowerCase() === u ? -1 : (c === u ? 1 : 0));
};

Based on Sonic Beard comment to the main answer. I changed the logic in the result:

  • 0: Lowercase

  • 1: Uppercase

  • -1: neither

pasx
  • 2,718
  • 1
  • 34
  • 26
1

Assuming that a string is only considered to not be all uppercase if at least one lowercase letter is present, this works fine. I understand it's not concise and succinct like everybody else tried to do, but does it works =)

function isUpperCase(str) {
    for (var i = 0, len = str.length; i < len; i++) {
        var letter = str.charAt(i);
        var keyCode = letter.charCodeAt(i);
        if (keyCode > 96 && keyCode < 123) {
            return false;
        }
    }

    return true;
}
Shedolamack
  • 319
  • 1
  • 4
1

I need to test against a string of any character (including white space, marks, numbers, unicode characters...). Because white space, numbers, marks... will be the same in both upper case and lower case, and I want to find real upper case letters, I do this:

let countUpperCase = 0;
let i = 0;
while (i <= string.length) {
  const character = string.charAt(i);
  if (character === character.toUpperCase() && character !== character.toLowerCase()) {
    countUpperCase++;
  }
  i++;
}
Tacaza
  • 539
  • 1
  • 4
  • 12
1

Another way is to compare the character with an empty object, i don't really know's why it works, but it works :

for (let i = 1; i <= 26; i++) {
   const letter = (i + 9).toString(36).toUpperCase();
   console.log('letter', letter, 'is upper', letter<{}); // returns true
}
for (let i = 1; i <= 26; i++) {
   const letter = (i + 9).toString(36);
   console.log('letter', letter, 'is upper', letter<{}); // returns false
}

so in a function :

function charIsUpper(character) {
   return character<{};
}

EDIT: it doesn't work with accents and diacritics, so it's possible to remove it

function charIsUpper(character) {
   return character
           .normalize('NFD')
           .replace(/[\u0300-\u036f]/g, '')<{};
}
Julien METRAL
  • 1,894
  • 13
  • 30
  • 2
    It works because the string representation of an object is `[object Object]`. You're basically checking if the character code of the letter comes before `[`. Since the character codes for `Z, [, a` are `90, 91, 97` respectively, the comparison is truthy for uppercase letters and falsy for lowercase letters. In other words, it's an equally hacky way of doing it as using base-36 numbers to get the letters of the alphabet. – radulfr Nov 04 '19 at 17:29
  • @radulfr Interessting thing, i thought it was something like that but i did not have the exact answer, effectively this method doesn't work with upper case accents but it's possible to unaccent it with something like that : `character.normalize("NFD").replace(/[\u0300-\u036f]/g` – Julien METRAL Nov 04 '19 at 18:06
1

Simply check the ASCII value

// IsLower verify that a string does not contains upper char
func IsLower(str string) bool {
    for i := range str {
        ascii := int(str[i])
        if ascii < 91 && ascii > 64 {
            return false
        }
    }
    return true
}
alessiosavi
  • 2,753
  • 2
  • 19
  • 38
0

One I use (notice this doesnt make "TestString" as "T est String" or " Test String").

function seperateCapitalised(capitalisedString) {
    if (typeof capitalisedString !== "string" || capitalisedString.length === 0)
        return capitalisedString;

    var newStr = capitalisedString[0];
    for (var i = 1; i < capitalisedString.length; i++) {
        var char = capitalisedString[i];

        if (char === char.toUpperCase() && isNaN(char)) {
            newStr += ' ' + char;
        }
        else {
            newStr += char;
        }
    }
    return newStr;
}
Fred Johnson
  • 2,539
  • 3
  • 26
  • 52
-1

Stephen Nelsons' function converted to a prototype with lots of test examples.

I've also added whole strings to the function for completeness.

See code for additional comments.

/* Please note, there's no requirement to trim any leading or trailing white
spaces. This will remove any digits in the whole string example returning the
correct result. */

String.prototype.isUpperCase = function(arg) {
var re = new RegExp('\\s*\\d+\\s*', 'g');
if (arg.wholeString) {return this.replace(re, '') == this.replace(re, '').toUpperCase()} else
return !!this && this != this.toLocaleLowerCase();
}

console.log('\r\nString.prototype.isUpperCase, whole string examples');
console.log(' DDD is ' + ' DDD'.isUpperCase( { wholeString:true } ));
console.log('9 is ' + '9'.isUpperCase( { wholeString:true } ));
console.log('Aa is ' + 'Aa'.isUpperCase( { wholeString:true } ));
console.log('DDD 9 is ' + 'DDD 9'.isUpperCase( { wholeString:true } ));
console.log('DDD is ' + 'DDD'.isUpperCase( { wholeString:true } ));
console.log('Dll is ' + 'Dll'.isUpperCase( { wholeString:true } ));
console.log('ll is ' + 'll'.isUpperCase( { wholeString:true } ));

console.log('\r\nString.prototype.isUpperCase, non-whole string examples, will only string on a .charAt(n) basis. Defaults to the first character');
console.log(' DDD is ' + ' DDD'.isUpperCase( { wholeString:false } ));
console.log('9 is ' + '9'.isUpperCase( { wholeString:false } ));
console.log('Aa is ' + 'Aa'.isUpperCase( { wholeString:false } ));
console.log('DDD 9 is ' + 'DDD 9'.isUpperCase( { wholeString:false } ));
console.log('DDD is ' + 'DDD'.isUpperCase( { wholeString:false } ));
console.log('Dll is ' + 'Dll'.isUpperCase( { wholeString:false } ));
console.log('ll is ' + 'll'.isUpperCase( { wholeString:false } ));

console.log('\r\nString.prototype.isUpperCase, single character examples');
console.log('BLUE CURAÇAO'.charAt(9) + ' is ' + 'BLUE CURAÇAO'.charAt(9).isUpperCase( { wholeString:false } ));
console.log('9 is ' + '9'.isUpperCase( { wholeString:false } ));
console.log('_ is ' + '_'.isUpperCase( { wholeString:false } ));
console.log('A is ' + 'A'.isUpperCase( { wholeString:false } ));
console.log('d is ' + 'd'.isUpperCase( { wholeString:false } ));
console.log('E is ' + 'E'.isUpperCase( { wholeString:false } ));
console.log('À is ' + 'À'.isUpperCase( { wholeString:false } ));
console.log('É is ' + 'É'.isUpperCase( { wholeString:false } ));
console.log('Ñ is ' + 'Ñ'.isUpperCase( { wholeString:false } ));
console.log('ñ is ' + 'ñ'.isUpperCase( { wholeString:false } ));
console.log('Þ is ' + 'Þ'.isUpperCase( { wholeString:false } ));
console.log('Ͻ is ' + 'Ͻ'.isUpperCase( { wholeString:false } ));
console.log('Ͽ is ' + 'Ͽ'.isUpperCase( { wholeString:false } ));
console.log('Ά is ' + 'Ά'.isUpperCase( { wholeString:false } ));
console.log('Έ is ' + 'Έ'.isUpperCase( { wholeString:false } ));
console.log('ϴ is ' + 'ϴ'.isUpperCase( { wholeString:false } ));
console.log('Ϋ is ' + 'Ϋ'.isUpperCase( { wholeString:false } ));
console.log('Ϣ is ' + 'Ϣ'.isUpperCase( { wholeString:false } ));
console.log('Ϥ is ' + 'Ϥ'.isUpperCase( { wholeString:false } ));
console.log('Ϧ is ' + 'Ϧ'.isUpperCase( { wholeString:false } ));
console.log('Ϩ is ' + 'Ϩ'.isUpperCase( { wholeString:false } ));
console.log('Ϫ is ' + 'Ϫ'.isUpperCase( { wholeString:false } ));
console.log('Ϭ is ' + 'Ϭ'.isUpperCase( { wholeString:false } ));
console.log('Ϯ is ' + 'Ϯ'.isUpperCase( { wholeString:false } ));
console.log('Ϲ is ' + 'Ϲ'.isUpperCase( { wholeString:false } ));
console.log('Ϸ is ' + 'Ϸ'.isUpperCase( { wholeString:false } ));
console.log('Ϻ is ' + 'Ϻ'.isUpperCase( { wholeString:false } ));
Ste
  • 1,729
  • 1
  • 17
  • 27