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

Javascript

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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

then :

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

Solution 6 - Javascript

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

Solution 7 - Javascript

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

Solution 8 - Javascript

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

Solution 9 - Javascript

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

Solution 10 - Javascript

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.

Solution 11 - Javascript

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.

Solution 12 - Javascript

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.

Solution 13 - Javascript

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

Solution 14 - Javascript

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

Solution 15 - Javascript

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

Solution 16 - Javascript

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

Solution 17 - Javascript

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

Solution 18 - Javascript

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

Solution 19 - Javascript

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)

Solution 20 - Javascript

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

Solution 21 - Javascript

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

Solution 22 - Javascript

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

Solution 23 - Javascript

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:

Solution 24 - Javascript

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

Solution 25 - Javascript

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

Solution 26 - Javascript

This is how I did it recently:

  1. Check that a char/string s is lowercase

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

  1. Check s is uppercase

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

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

Solution 27 - Javascript

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

Solution 28 - Javascript

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

Solution 29 - Javascript

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
}

Solution 30 - Javascript

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

Solution 31 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoeView Question on Stackoverflow
Solution 1 - JavascriptDing PogiView Answer on Stackoverflow
Solution 2 - JavascriptDaniel VandersluisView Answer on Stackoverflow
Solution 3 - JavascriptWebFreak001View Answer on Stackoverflow
Solution 4 - JavascriptciemborView Answer on Stackoverflow
Solution 5 - JavascriptAbdennour TOUMIView Answer on Stackoverflow
Solution 6 - JavascriptJoshView Answer on Stackoverflow
Solution 7 - JavascriptKooiIncView Answer on Stackoverflow
Solution 8 - JavascriptArthur van AckerView Answer on Stackoverflow
Solution 9 - JavascriptMalekiView Answer on Stackoverflow
Solution 10 - JavascriptStephen NelsonView Answer on Stackoverflow
Solution 11 - JavascriptNatView Answer on Stackoverflow
Solution 12 - JavascriptJamesView Answer on Stackoverflow
Solution 13 - JavascriptGiboltView Answer on Stackoverflow
Solution 14 - JavascriptHimanshu TeotiaView Answer on Stackoverflow
Solution 15 - JavascriptZachary PuthoffView Answer on Stackoverflow
Solution 16 - JavascriptSonic BeardView Answer on Stackoverflow
Solution 17 - JavascriptHuy DoView Answer on Stackoverflow
Solution 18 - JavascriptfarhanahmedhasanView Answer on Stackoverflow
Solution 19 - Javascriptuser3449311View Answer on Stackoverflow
Solution 20 - JavascriptFeniciView Answer on Stackoverflow
Solution 21 - JavascriptMatthewView Answer on Stackoverflow
Solution 22 - JavascriptpasxView Answer on Stackoverflow
Solution 23 - JavascriptJensView Answer on Stackoverflow
Solution 24 - JavascriptShedolamackView Answer on Stackoverflow
Solution 25 - JavascriptTacazaView Answer on Stackoverflow
Solution 26 - JavascriptCristian PascuView Answer on Stackoverflow
Solution 27 - JavascriptjstmView Answer on Stackoverflow
Solution 28 - JavascriptJulien METRALView Answer on Stackoverflow
Solution 29 - JavascriptalessiosaviView Answer on Stackoverflow
Solution 30 - JavascriptFred JohnsonView Answer on Stackoverflow
Solution 31 - JavascriptSteView Answer on Stackoverflow