p.campbell
p.campbell

Reputation: 100567

JavaScript - checking for any lowercase letters in a string

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?

Upvotes: 66

Views: 115000

Answers (4)

karim79
karim79

Reputation: 342635

function hasLowerCase(str) {
    return str.toUpperCase() != str;
}

console.log("HeLLO: ", hasLowerCase("HeLLO"));
console.log("HELLO: ", hasLowerCase("HELLO"));

Upvotes: 169

Ratan Paul
Ratan Paul

Reputation: 492

Another solution only match regex to a-z

function nameHere(str) {
    return str.match(/[a-z]/);
}

or

 function nameHere(str) {
        return /[a-z]/g.test(str);
    }

Upvotes: 1

John ClearZ
John ClearZ

Reputation: 1001

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

Upvotes: 7

ariel
ariel

Reputation: 16150

also:

function hasLowerCase(str) {
    return (/[a-z]/.test(str));
}

Upvotes: 69

Related Questions