AGamePlayer
AGamePlayer

Reputation: 7736

What is the best way to check whether a string is all upper-case in JavaScript:

I have searched it for a while. But there are no perfect answers.

For example, someone says I can use:

function isUpperCase(str) {
    return str === str.toUpperCase();
}

This works for a simple case, but not for complicated ones.

For instance:

isUpperCase('ABC'); // works good
isUpperCase('ABcd'); // works good too
isUpperCase('汉字'); // not working, should be false.

Upvotes: 5

Views: 1431

Answers (5)

Unamata Sanatarai
Unamata Sanatarai

Reputation: 6637

First of all, your code seems to be working just fine.

Lower case characters for 汉字 and upper case characters for 汉字 have the same numeric value, as seen here:

var str = '汉字';
for (i = 0; i < str.length; i++){
    console.log(str[i], str.charCodeAt(i), str.toUpperCase().charCodeAt(i),str.toLowerCase().charCodeAt(i))
}

let's compare this result with some other string:

    var str = 'łóÐŻCakf8';
    for (i = 0; i < str.length; i++){
        console.log(str[i], str.charCodeAt(i), str.toUpperCase().charCodeAt(i),str.toLowerCase().charCodeAt(i))
    }

Upvotes: 0

Sameer Carpenter
Sameer Carpenter

Reputation: 128

Try this

function isUpperCase(str){
   for (i = 0; i < str.length; i++) { 
    var charCode=str.charCodeAt(i);
         if(charCode<65||charCode>90){
            return false;
          }
      }
     return true;
   }

You can check the letters by ascii code.

Upvotes: 0

dolphin
dolphin

Reputation: 132

You can try regex approach.

   const isUpperCase2 = (string) => /^[A-Z]*$/.test(string);
   isUpperCase2('ABC'); // true
   isUpperCase2('ABcd'); // false
   isUpperCase2('汉字'); // false

Hope this help;

Upvotes: 2

guest271314
guest271314

Reputation: 1

RegExp /^[A-Z]+$/ returns expected result

const isUpperCase = str => /^[A-Z]+$/.test(str);

console.log(
  isUpperCase("ABC")
  , isUpperCase("ABcd")
  , isUpperCase("汉字")
);

Upvotes: 5

Bruno Grieder
Bruno Grieder

Reputation: 29814

How about

function isUpperCase(str) {
    return str === str.toUpperCase() && str !== str.toLowerCase();
}

to match the last one

Upvotes: 5

Related Questions