Write A Javascript Program To Test The First Character Of A String Is Uppercase Or Not

Write A Javascript Program To Test The First Character Of A String Is Uppercase Or Not

3 min read Jun 18, 2024
Write A Javascript Program To Test The First Character Of A String Is Uppercase Or Not

JavaScript Program to Test the First Character of a String is Uppercase or Not

This program will determine whether the first character of a given string is uppercase or lowercase.

function isUppercase(str) {
  if (str.length === 0) {
    return false; // Empty string, no first character
  }
  return str[0] === str[0].toUpperCase(); // Compare the first character to its uppercase version
}

// Test Cases
console.log(isUppercase("Hello")); // true
console.log(isUppercase("world")); // false
console.log(isUppercase("123")); // false
console.log(isUppercase("")); // false

Explanation:

  1. isUppercase(str) function:

    • Takes a string (str) as input.
    • Checks if the string is empty (str.length === 0). If empty, returns false since there's no first character.
    • Uses str[0] to access the first character of the string.
    • Compares the first character (str[0]) with its uppercase version (str[0].toUpperCase()).
    • Returns true if they are equal (meaning the first character was uppercase), otherwise returns false.
  2. Test Cases:

    • Demonstrates the function's usage with different string inputs and their corresponding outputs.

How it works:

  • The toUpperCase() method converts a character to its uppercase equivalent.
  • By comparing the original character with its uppercase version, we determine if it was already uppercase.
  • If the comparison is true, it means the first character was uppercase.

Alternative Method (Using Regex):

function isUppercase(str) {
  if (str.length === 0) {
    return false;
  }
  return /^[A-Z]/.test(str); // Use regex to match the first character against uppercase letters
}

This alternative uses a regular expression (^[A-Z]) to check if the first character matches an uppercase letter. This approach is more concise and potentially faster in some scenarios.