string 如何在 JavaScript 中检查字符串是否全部为大写?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17572873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:00:55  来源:igfitidea点击:

How can I check if a string is all uppercase in JavaScript?

javascriptstring

提问by Danilo

There is a Javascript/Jquery boolean function to test if a string is all uppercase?

有一个 Javascript/Jquery 布尔函数来测试字符串是否全部为大写?

example of matching:

匹配示例:

"hello" => false
"Hello" => false
"HELLO" => true

回答by Andrew Whitaker

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


isUpperCase("hello"); // false
isUpperCase("Hello"); // false
isUpperCase("HELLO"); // true

You could also augment String.prototype:

你也可以增加String.prototype

String.prototype.isUpperCase = function() {
    return this.valueOf().toUpperCase() === this.valueOf();
};


"Hello".isUpperCase(); // false
"HELLO".isUpperCase(); // true

回答by Danilo

I must write at least one sentence here, because they don't like short answers here, but this is simplest solution I can think of:

我必须在这里至少写一句话,因为他们不喜欢这里的简短答案,但这是我能想到的最简单的解决方案:

s.toUpperCase() === s

s.toUpperCase() === s

回答by Dan Tao

Here's another option:

这是另一种选择:

function isUpperCase(str) {
  return (/^[^a-z]*$/).test(str);
}

回答by A. Wolff

Just use:

只需使用:

if(mystring === mystring.toUpperCase())

回答by Snake Eyes

var test = "HELLO";
var upper = test.toUpperCase();

return test === upper; // true

// other example

var test = "Hello";
var upper = test.toUpperCase();

return test === upper; // false