views:

136

answers:

3

Consider a JavaScript method that needs to check whether a given string is in all uppercase letters. The input strings are people's names.

The current algorithm is to check for any lowercase letters.

var check1 = "Jack Spratt";    
var check2 = "BARBARA FOO-BAR"; 
var check3 = "JASON D'WIDGET";  

var isUpper1 = HasLowercaseCharacters(check1);  
var isUpper2 = HasLowercaseCharacters(check2);
var isUpper3 = HasLowercaseCharacters(check3);

function HasLowercaseCharacters(string input)
{
    //pattern for finding whether any lowercase alpha characters exist
    var allLowercase; 

    return allLowercase.test(input);
}

Is a regex the best way to go here?

What pattern would you use to determine whether a string has any lower case alpha characters?

+12  A: 
function hasLowerCase(str) {
    if(str.toUpperCase() != str) {
        return true;
    }
    return false;
}

alert(hasLowerCase("HeLLO"));
alert(hasLowerCase("HELLO"));

Try it: http://jsfiddle.net/B2bvY/3/

karim79
+3  A: 

also:

function hasLowerCase(str) {
    return (/[a-z]/.test(str));
}
bortao
That's a very English-centric view of what a lowercase letter is. Is "à" not lower case? I'm mentioning this so long after this answer was accepted because this question has been referenced by [this newer question](http://stackoverflow.com/questions/3816905). The `!= toUpperCase` answer below is much more inclusive.
T.J. Crowder
+2  A: 
function hasLowerCase(str) {
    return str.toUpperCase() != str;
}

or

function hasLowerCase(str) {
    for(x=0;x<str.length;x++)
        if(str.charAt(x) >= 'a' && str.charAt(x) <= 'z')
            return true;
    return false;
}
John ClearZ