Check if first letter of word is a capital letter

后端 未结 8 1212
春和景丽
春和景丽 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:37
    var string1 = "this is a string";
    var string2 = "This is a string";
    
    if(string1[0] == string1[0].toUpperCase())
        alert('is upper case');
    else
        alert('is not upper case');
    
    
    if(string2[0] == string2[0].toUpperCase())
        alert('is upper case');
    else
        alert('is not upper case');
    
    0 讨论(0)
  • 2020-12-07 22:39

    Using the match method of the string object prototype:

    const word = 'Someword';
    console.log(word.match(new RegExp(/^[A-Z]/)) !== null);
    
    0 讨论(0)
  • 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 */ }
    
    0 讨论(0)
  • 2020-12-07 22:48

    Yes.

    var str = "Hello";
    if(str[0].toUpperCase() == str[0])
    {
       window.alert('First character is upper case.');  
    }
    
    0 讨论(0)
  • 2020-12-07 22:57

    For English letters only:

    'A' => 65
    'Z' => 90
    

    Meaning, every number between [65, 90] is a capital letter:

    function startsWithCapitalLetter(word) {
      return word.charCodeAt(0) >= 65 && word.charCodeAt(0) <= 90;
    }
    
    0 讨论(0)
  • 2020-12-07 22:59
    var word = "Someword";
    console.log( word[0] === word[0].toUpperCase() );
    

    or

    var word = "Someword";
    console.log( /[A-Z]/.test( word[0]) );
    

    or

    var word = "Someword";
    console.log( /^[A-Z]/.test( word) );
    

    See toUpperCase() and test()

    0 讨论(0)
提交回复
热议问题