Check if first letter of word is a capital letter

后端 未结 8 1239
春和景丽
春和景丽 2020-12-07 22:07

Is it possible in Javascript to find out if the first letter of a word is a capital letter?

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-07 22:46

    You can do it in several ways:

    var myWord = "Hello";
    
    // with string functions
    if (myWord.charAt(0) === myWord.charAt(0).toUpperCase()) { /* is upper */ }
    
    // or for newer browsers that support array-style access to string characters
    if (myWord[0] === myWord[0].toUpperCase()) { /* is upper */ }
    
    // with regex - may not be appropriate for non-English uppercase
    if (/^[A-Z]/.test(myWord) { /* is upper */ }
    

    Note that the array-style access to characters like myWord[0] is an ECMAScript 5 feature and not supported in older browsers, so (for now) I'd probably recommend the .charAt() method.

    If you need to do this test a lot you could make a little function:

    function firstLetterIsUpper(str) {
       var f = str.charAt(0);   // or str[0] if not supporting older browsers
       return f.toUpperCase() === f;
    }
    
    if (firstLetterIsUpper(myWord)) { /* do something */ }
    

提交回复
热议问题