如何知道所有字符是否都在字符串中大写?

时间:2013-07-01 13:34:07

标签: javascript string

如何判断所有字母是否在字符串中大写?

像:

var someVar = 'AAAAA DDSSS asssd';

或者只有超过80%的字母大写?

2 个答案:

答案 0 :(得分:4)

我建议:

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);

JS Fiddle demo

或者,如果您想要具有固定的准确度:

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);

JS Fiddle demo

稍微有用(因为它我们也会删除空白和小写),只需进行简单的检查以避免执行不必要的数学运算:

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);

JS Fiddle demo

参考文献:

答案 1 :(得分:1)

您可以尝试这样的事情

if (myString == myString.toUpperCase())
{
  alert('all upper case');
}

这将检查完整的大写字符串。如果你想检查80%,那么你需要做一些数学逻辑,循环遍历每个角色。