What is the best way to check if a string is uppercase in JavaScript:

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

For example, someone says that I can use:

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

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

For instance:

isUpperCase('ABC'); // works good
isUpperCase('ABcd'); // works good too
isUpperCase('汉字'); // not working, should be false.
+4
source share
5 answers

What about

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

to match the last

+4
source

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

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

console.log(
  isUpperCase("ABC")
  , isUpperCase("ABcd")
  , isUpperCase("汉字")
);
Run codeHide result
+4
source

regex.

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

;

+2

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

ascii.

0

, .

汉字 汉字 , :

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

compare this result with some other line:

    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))
    }
Run codeHide result
0
source

Source: https://habr.com/ru/post/1686937/


All Articles