Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.
like image 699
AGamePlayer Avatar asked Oct 05 '17 06:10

AGamePlayer


3 Answers

How about

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

to match the last one

like image 79
Bruno Grieder Avatar answered Oct 18 '22 01:10

Bruno Grieder


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

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

console.log(
  isUpperCase("ABC")
  , isUpperCase("ABcd")
  , isUpperCase("汉字")
);
like image 5
guest271314 Avatar answered Oct 18 '22 02:10

guest271314


You can try regex approach.

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

Hope this help;

like image 2
dolphin Avatar answered Oct 18 '22 01:10

dolphin