简体   繁体   中英

Javascript Function that returns true if a letter?

So I'm looking to write a function for my class that is titled isAlpha that accepts a character (preferably a string with length of 1) and returns true if it's a letter and false if it's not.

The thing is I'm completely stuck on where to go. This is the example the instructor gave in class:

var isAlpha = function(ch){

     //if ch is greater than or equal to "a" AND
    // ch is less than or equal to "z" then it is alphabetic

}

var ltr ="a", digit =7;
alert(isAlpha(ltr));
alert(isAlpha(digit))

I'm not sure what to do with that though, I've tried a few different things like:

var isAlpha = function(ch){
    if (ch >= "A" && ch <= "z"){
        return true
    }

}
alert(isAlpha(ch))

Can anyone point me in the right direction of how to this function started?

You could just use a case-insensitive regular expression :

var isAlpha = function(ch){
  return /^[A-Z]$/i.test(ch);
}

If you are supposed to be following the instructions in the comments about greater than and less than comparisons, and you want to check that the input is a string of length 1, then:

 var isAlpha = function(ch){ return typeof ch === "string" && ch.length === 1 && (ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z"); } console.log(isAlpha("A")); // true console.log(isAlpha("a")); // true console.log(isAlpha("[")); // false console.log(isAlpha("1")); // false console.log(isAlpha("ABC")); // false because it is more than one character

You'll notice I didn't use an if statement. That's because the expression ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z" ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z" evaluates to be either true or false , so you can simply return that value directly.

What you had tried with if (ch >= "A" && ch <= "z") doesn't work because the range of characters in between an uppercase "A" and a lowercase "z" includes not only letters but some other characters that are between "Z" and "a".

First make sure it is a string, then use regex.

var isAlpha = function(ch){
  return typeof ch === "string" && ch.length === 1 && /[A-Za-z]/.test(ch);
}

if it's only one character you need:

var isAlpha = function(ch){
  return /^[A-Za-z]{1,1}$/.test(ch)
}

notice that the {1,1} here means the character appears at least once and at most once. If you only test one character you can just remove this {1,1} , if you want to test more than one character, you can update this into {n,m} according to your requirement.

The regex is your friend.

var isAlpha = function(ch){

     return ch.match(/[0-9]/) != null

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM