Is uppercase used correctly JavaScript

In JavaScript, we can determine whether a string follows correct uppercase usage based on three specific rules. A string is considered to have correct uppercase usage if it meets any of these criteria:

  • All letters in a word are capitals, like "INDIA".
  • All letters in a word are not capitals, like "example".
  • Only the first letter in a word is capital, like "Ramesh".

We need to write a JavaScript function that takes a string and determines whether it complies with any of these three rules, returning true if it does, false otherwise.

Using Loop-Based Approach

Here's a function that checks each character to validate the uppercase usage:

const detectCapitalUse = (word = '') => {
    let allCap = true;
    for (let i = 0; i  1)
                return false;
            else allCap = false;
        };
    };
    return true;
};

console.log(detectCapitalUse('INDIA'));    // All uppercase
console.log(detectCapitalUse('jdsdS'));    // Mixed case (invalid)
console.log(detectCapitalUse('dsdsdsd'));  // All lowercase
console.log(detectCapitalUse('Ramesh'));   // First letter capital
true
false
true
true

Using Regular Expressions

A more concise approach using regular expressions to match the three valid patterns:

const detectCapitalUseRegex = (word) => {
    // Pattern 1: All uppercase
    const allUpper = /^[A-Z]+$/;
    // Pattern 2: All lowercase  
    const allLower = /^[a-z]+$/;
    // Pattern 3: First letter uppercase, rest lowercase
    const firstUpper = /^[A-Z][a-z]*$/;
    
    return allUpper.test(word) || allLower.test(word) || firstUpper.test(word);
};

console.log(detectCapitalUseRegex('HELLO'));   // All uppercase
console.log(detectCapitalUseRegex('world'));   // All lowercase
console.log(detectCapitalUseRegex('JavaScript')); // First capital
console.log(detectCapitalUseRegex('javaScript')); // Invalid pattern
true
true
true
false

How It Works

The loop-based approach tracks whether all characters seen so far are uppercase using the allCap flag. When it encounters a lowercase letter, it checks if this violates the rules. The regex approach directly matches against the three valid patterns using separate regular expressions.

Comparison

Method Readability Performance Code Length
Loop-based Moderate Good Longer
Regular Expression High Good Shorter

Conclusion

Both approaches effectively validate uppercase usage in strings. The regular expression method offers cleaner, more readable code, while the loop-based approach provides more granular control over the validation logic.

Updated on: 2026-03-15T23:19:00+05:30

118 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements