如何确定字符串中的所有字母是否都大写?
像:
var someVar = 'AAAAA DDSSS asssd';
还是只有超过 80% 的字母大写?
我建议:
function capitalized (str) {
var len = str.length,
noCapitals = str.replace(/[a-z]/g,''),
percent = (noCapitals.length/len) * 100;
return percent;
}
var someVar = 'AAAAA DDSSS addes',
p = capitalized(someVar);
console.log(p);
或者,如果您想获得固定精度:
function capitalized (str) {
var len = str.length,
noCapitals = str.replace(/[a-z]/g,''),
percent = (noCapitals.length/len) * 100;
return parseFloat(percent.toFixed(2));
}
var someVar = 'AAAAA DDSSS addes',
p = capitalized(someVar);
console.log(p);
并且更有用(因为我们还去掉了空格和小写字母),通过简单的检查来避免执行不必要的数学运算:
function capitalized (str) {
var len = str.length,
noCapitals = str.replace(/[a-z]\s/g,''),
percent = noCapitals.length === 0 ? 100 : (noCapitals.length/len) * 100;
return parseFloat(percent.toFixed(2));
}
var someVar = 'AAAAA DDSSS',
p = capitalized(someVar);
console.log(p);
参考:
你可以试试这样的
if (myString == myString.toUpperCase())
{
alert('all upper case');
}
这将检查完整的大写字符串。如果你想检查 80% 那么你需要做一些数学逻辑,循环遍历每个字符。