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

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

This question is related to javascript

The answer is


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


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;
    }

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'); 
}

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}`)

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
};


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.


function isUpperCase(myString) { 
  return (myString == myString.toUpperCase()); 
} 
function isLowerCase(myString) { 
  return (myString == myString.toLowerCase()); 
} 

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

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


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

if (character == character.toLowerCase())
{
  // The character is lowercase
}
else
{
  // The character is uppercase
}

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.


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. ;)


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()); 
}

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:).


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.


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;
}

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++;
}

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

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)

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:

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


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
}

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;
}

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.


function isCapital(ch){
    return ch.charCodeAt() >= 65 && ch.charCodeAt() <= 90;
}

const isUpperCase = (string) => /^[A-Z]*$/.test(string)

then :

isUpperCase('A') // true
isUpperCase('a') // false

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, '')<{};
}

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.

_x000D_
_x000D_
/* Please note, there's no requirement to trim any leading or trailing white_x000D_
spaces. This will remove any digits in the whole string example returning the_x000D_
correct result. */_x000D_
_x000D_
String.prototype.isUpperCase = function(arg) {_x000D_
var re = new RegExp('\\s*\\d+\\s*', 'g');_x000D_
if (arg.wholeString) {return this.replace(re, '') == this.replace(re, '').toUpperCase()} else_x000D_
return !!this && this != this.toLocaleLowerCase();_x000D_
}_x000D_
_x000D_
console.log('\r\nString.prototype.isUpperCase, whole string examples');_x000D_
console.log(' DDD is ' + ' DDD'.isUpperCase( { wholeString:true } ));_x000D_
console.log('9 is ' + '9'.isUpperCase( { wholeString:true } ));_x000D_
console.log('Aa is ' + 'Aa'.isUpperCase( { wholeString:true } ));_x000D_
console.log('DDD 9 is ' + 'DDD 9'.isUpperCase( { wholeString:true } ));_x000D_
console.log('DDD is ' + 'DDD'.isUpperCase( { wholeString:true } ));_x000D_
console.log('Dll is ' + 'Dll'.isUpperCase( { wholeString:true } ));_x000D_
console.log('ll is ' + 'll'.isUpperCase( { wholeString:true } ));_x000D_
_x000D_
console.log('\r\nString.prototype.isUpperCase, non-whole string examples, will only string on a .charAt(n) basis. Defaults to the first character');_x000D_
console.log(' DDD is ' + ' DDD'.isUpperCase( { wholeString:false } ));_x000D_
console.log('9 is ' + '9'.isUpperCase( { wholeString:false } ));_x000D_
console.log('Aa is ' + 'Aa'.isUpperCase( { wholeString:false } ));_x000D_
console.log('DDD 9 is ' + 'DDD 9'.isUpperCase( { wholeString:false } ));_x000D_
console.log('DDD is ' + 'DDD'.isUpperCase( { wholeString:false } ));_x000D_
console.log('Dll is ' + 'Dll'.isUpperCase( { wholeString:false } ));_x000D_
console.log('ll is ' + 'll'.isUpperCase( { wholeString:false } ));_x000D_
_x000D_
console.log('\r\nString.prototype.isUpperCase, single character examples');_x000D_
console.log('BLUE CURAÇAO'.charAt(9) + ' is ' + 'BLUE CURAÇAO'.charAt(9).isUpperCase( { wholeString:false } ));_x000D_
console.log('9 is ' + '9'.isUpperCase( { wholeString:false } ));_x000D_
console.log('_ is ' + '_'.isUpperCase( { wholeString:false } ));_x000D_
console.log('A is ' + 'A'.isUpperCase( { wholeString:false } ));_x000D_
console.log('d is ' + 'd'.isUpperCase( { wholeString:false } ));_x000D_
console.log('E is ' + 'E'.isUpperCase( { wholeString:false } ));_x000D_
console.log('À is ' + 'À'.isUpperCase( { wholeString:false } ));_x000D_
console.log('É is ' + 'É'.isUpperCase( { wholeString:false } ));_x000D_
console.log('Ñ is ' + 'Ñ'.isUpperCase( { wholeString:false } ));_x000D_
console.log('ñ is ' + 'ñ'.isUpperCase( { wholeString:false } ));_x000D_
console.log('Þ is ' + 'Þ'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));_x000D_
console.log('? is ' + '?'.isUpperCase( { wholeString:false } ));
_x000D_
_x000D_
_x000D_