3

Possible Duplicate:
Check if first letter of word is a capital letter

I want to write a function in which I pass string as argument. Then I want to find out whether the first letter of this string is capital or not. If it is capital then return true otherwise return false. How can I achieve this in javascript? Any simple demo, I will later modify according to my need.

Community
  • 1
  • 1
Om3ga
  • 30,465
  • 43
  • 141
  • 221
  • Are you asking to check if the first *character* is a letter and is capital, or if merely the first letter of the string is capital? Those are two different things. Given your question, the following string should return true `"...123Abc"` – I Hate Lazy Dec 06 '12 at 13:09

4 Answers4

4
var myString = "Whatever you want to test"
console.log(myString[0] == myString[0].toUpperCase());
//Returns true

myString = "whatever you want to test"
console.log(myString[0] == myString[0].toUpperCase());
//Returns false

myString[0] doesn't work in (Somewhere around) IE7/IE8 and lower, use myString.charAt(0) if you need the script to be compatible with those browsers.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
4

You can use String.charCodeAt(). This function returns a a unicode value of the character. Uppercase letters have a different value than lowercase ones.

Check the docs: http://dochub.io/#javascript/string.charcodeat

function isFirstLetterCapital(string) {
  return string.charCodeAt(0) === string.toUpperCase().charCodeAt(0);
}

Edit:

charAt is actually faster - http://jsperf.com/string-operations-order. Thanks Cerbrus for pointing this out.

function isFirstLetterCapital(string) {
  return string.charAt(0) === string.charAt(0).toUpperCase();
}
piatek
  • 376
  • 1
  • 6
3
if(yourString.match(/^[A-Z]/)) ...
Samuel Caillerie
  • 8,259
  • 1
  • 27
  • 33
1
function isFirstLetterUpperCase(string) {
   var firstLetter = string.charAt(0);
   return firstLetter == firstLetter.toUpperCase();
}
Magus
  • 14,796
  • 3
  • 36
  • 51