How can I test if a letter in a string is uppercase or lowercase using JavaScript?
views:
2197answers:
6function isUpperCase(myString) {
return (myString == myString.toUpperCase());
}
function isLowerCase(myString) {
return (myString == myString.toLowerCase());
}
if (character == character.toLowerCase())
{
// The character is lowercase
}
else
{
// The character is uppercase
}
String.prototype.isUpper = function(pos){return this.charCodeAt(pos)<90;};
alert('stringIsUpperCaseTest'.isUpper(7)); //true
String.prototype.isUpper performs a very simple test. It's just the idea, you can figure out yourself how to exclude non alphabetic characters (65-90 = uppercase A-Z, 97-122 = lowercase a-z) I suppose. Or indeed, use
String.prototype.isUpper = function(pos){
var chr= this.charAt(pos);
return chr === chr.toLowerCase();
};
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());
}
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 ch=''; while (i <= strings.length){ character = strings.charAt(i); if (!isNaN(character * 1)){ alert('character is numric'); }else{ if (character == character.toUpperCase()) { alert ('upper case true'); } if (character == character.toLowerCase()){ alert ('lower case true'); } } i++; }
Regular Expressions anyone. This is how you perfectly do this with RegExp:
var check = /[:lower:]/;
alert(check.test("R")); //False
alert(check.test("r")); //True
alert(check.test("1")); //False