Is uppercase used correctly JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

For the purpose of this very problem, we define the correct use of uppercase letter by the following rules −

  • 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 are required to write a JavaScript function that takes in a string determines whether or not the string complies with any of these three rules.

If it does then we return true, false otherwise.

Example

const detectCapitalUse = (word = '') => {
   let allCap = true;
   for (let i = 0; i < word.length; i++){
      if (word.charAt(i) === word.charAt(i).toUpperCase()){
         if (allCap) continue;
            else return false;
      }
      else {
         if (allCap && i > 1)
            return false;
         else allCap = false;
      };
   };
   return true;
};
console.log(detectCapitalUse('INDIA'));
console.log(detectCapitalUse('jdsdS'));
console.log(detectCapitalUse('dsdsdsd'));

Output

And the output in the console will be −

true
false
true
raja
Updated on 21-Nov-2020 06:06:58

Advertisements