469

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

5
  • 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, 2009 at 14:02
  • 3
    jsperf.com/isupper-comparison/5 A few ideas there, and you can test them for speed as well. Jan 16, 2012 at 18:41
  • 2
    Idea #4 ([:upper:]) is fast and very cool except that it doesn't work, see my comment below and my corrected jsperf.com/isupper-comparison/7. Jun 12, 2013 at 12:34
  • 9
    str == str.toUpperCase(); returns true or false
    – Jacksonkr
    Sep 20, 2017 at 13:52
  • 2
    str.toUpperCase() === str && str.toLowerCase() !== str, if you really don't want to use regExp. Apr 17, 2021 at 11:59

32 Answers 32

494

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++;
}
12
  • 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, 2011 at 14:25
  • 6
    @LarsH see this: stackoverflow.com/questions/1027224/…
    – ciembor
    Mar 15, 2012 at 21:32
  • 1
    This code will alert that punctuation characters like ! are numeric.
    – Barmar
    May 23, 2014 at 4:16
  • 1
    Why not check both whether the char equals its own lowercase and uppercase, if both are true, then false.
    – user1663023
    Oct 10, 2017 at 0:01
  • Uncaught SyntaxError: Unexpected token ; at line 4 while (i &lt;= strings.length){ this line has some gibberish
    – giorgio79
    Nov 24, 2017 at 8:53
92

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])

9
  • 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 9, 2016 at 14:31
  • Sorry but this seems to be a duplicate of another three year old answer. Jun 9, 2018 at 6: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. Jun 10, 2018 at 10:24
  • Convert the entire string just in order to check the ASCII value of one character? Wasteful.
    – Engineer
    Aug 16, 2019 at 14:31
  • function isLowerCase(str) { return str == str.toLowerCase() }
    – latitov
    May 4, 2021 at 17:57
87
if (character == character.toLowerCase())
{
  // The character is lowercase
}
else
{
  // The character is uppercase
}
0
70
const isUpperCase = (string) => /^[A-Z]*$/.test(string)

then :

isUpperCase('A') // true
isUpperCase('a') // false
6
  • 5
    best answer by far, fast, not allocating any memory, or transforming data. Sep 6, 2018 at 22:19
  • 8
    Not working with accented characters (á, Á), vowel mutations (öÖ, äÄ, üÜ) and graphemes (ß,ẞ) tho.
    – NullDev
    Aug 16, 2020 at 14:57
  • Are you sure this is Go, and not JS?
    – latitov
    May 4, 2021 at 17:59
  • 3
    @latitov what do you mean? This is plain JavaScript. Jun 17, 2021 at 7: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 at 0:00
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:).

3
  • 1
    BTW, also works with accented characters like "É", "Ñ", and "ñ".
    – Xavi
    Nov 17, 2013 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 5, 2015 at 19:22
  • 3
    Okay, try this: შეარჩიე კატეგორიების მიხედვით
    – vovchisko
    Nov 21, 2020 at 21:18
25
function isUpperCase(myString) { 
  return (myString == myString.toUpperCase()); 
} 
function isLowerCase(myString) { 
  return (myString == myString.toLowerCase()); 
} 
8
  • 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, 2009 at 13:41
  • 5
    @zaczap - incorrect. These will transform (and then test) the entire string.
    – scunliffe
    Jun 22, 2009 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, 2009 at 13:47
  • 3
    Let's not forget strict equality checking! === FTW!
    – James
    Jun 22, 2009 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, 2009 at 13:52
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

3
  • 2
    @LarsH: I altered (and simplified) the prototype method. Now it includes diacriticals
    – KooiInc
    Jun 5, 2014 at 7:13
  • 1
    Why the comparision && chr === chr.toUpperCase();?? Apr 6, 2017 at 13:25
  • 3
    @Flame_Phoenix The range \u0080-\u024F may contain lower case diacriticals, so the test should also check the character itself.
    – KooiInc
    Apr 6, 2017 at 16:08
19
function isCapital(ch){
    return ch.charCodeAt() >= 65 && ch.charCodeAt() <= 90;
}
1
  • 3
    Or just return (ch.charCodeAt() >= 65 && ch.charCodeAt() <= 90).
    – Engineer
    Jul 17, 2019 at 10:52
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()); 
}
1
  • === for best practice
    – РАВИ
    Aug 20, 2016 at 1:17
10

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:

1
  • For future me: /\p{Lu}/u is equivalent to /\p{Uppercase_Letter}/u.
    – Nexus
    Sep 20 at 17:07
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.

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.

4
  • @RobertReiz Really? This doesn't work for non-Roman characters.
    – Barmar
    May 23, 2014 at 4: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 1, 2015 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). Jan 15, 2022 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). Apr 7 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.

3
  • 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, 2017 at 4: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, 2019 at 14:29
  • @Engineer, but Acker's answer is wrong "É" is not lower case.
    – James
    Aug 19, 2019 at 10:29
6

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
}
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));
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'); 
}
1
  • Add some explanation with answer for how this answer help OP in fixing current issue Jan 30, 2017 at 16:19
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;
    }
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}`)
2
  • Please update your answer with some comments about your code and how does it answers the question. Jan 12, 2021 at 7:21
  • This code will check the first character of the string for uppercase, lowercase, digit, and other.
    – Huy Do
    Jan 13, 2021 at 20:00
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)
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
0
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
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
};

1
  • 1
    Like that you put in your 2¢ Jun 26, 2019 at 19:35
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

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;
}
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++;
}
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
}
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, '')<{};
}
2
  • 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 4, 2019 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 Nov 4, 2019 at 18:06
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;
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.