JavaScript – Check if String starts with Uppercase Character

To check if given string starts with an uppercase character, in JavaScript, compare the first character in the string with its uppercase version. If the first character is already an uppercase character, then it matches with the uppercase version.

The boolean expression (or condition) to check if the string str starts with an uppercase character is

</>
Copy
str[0] === str[0].toUpperCase()

The following is a quick example to check if the string str1 starts with an uppercase character in JavaScript.

</>
Copy
var str = 'Hello world';
if ( str[0] === str[0].toUpperCase() ) {
    //string starts with an uppercase
} else {
    //string does not start with an uppercase
}

Examples

In the following example, we take a string in str and check if this string starts with an uppercase.

index.html

<!DOCTYPE html>
<html>
  <body>
    <pre id="output"></pre>
    <script>
      var str = 'Apple';
      if ( str[0] === str[0].toUpperCase() ) {
        displayOutput = 'string starts with an uppercase.';
      } else {
        displayOutput = 'string does not start with an uppercase.';
      }
      document.getElementById('output').innerHTML = displayOutput;
    </script>
  </body>
</html>

Now, let us take a value in the string, such that the string does not start with an uppercase character.

index.html

<!DOCTYPE html>
<html>
  <body>
    <pre id="output"></pre>
    <script>
      var str = 'apple';
      if ( str[0] === str[0].toUpperCase() ) {
        displayOutput = 'string starts with an uppercase.';
      } else {
        displayOutput = 'string does not start with an uppercase.';
      }
      document.getElementById('output').innerHTML = displayOutput;
    </script>
  </body>
</html>

Conclusion

In this JavaScript Tutorial, we learned how to check if a given string starts with an uppercase character, using String.toUpperCase() method and Equal-to operator, with examples.