67
votes

How to check if a string contains [a-zA-Z] characters only?

Example:

var str = '123z56';
6
an internationalized version of this question stackoverflow.com/questions/2013451/…Adrien Be

6 Answers

119
votes

No jQuery Needed

if (str.match(/[a-z]/i)) {
    // alphabet letters found
}
47
votes

You can use regex:

/[a-z]/i.test(str);

The i makes the regex case-insensitive. You could also do:

/[a-z]/.test(str.toLowerCase());
12
votes

Ahh, found the answer myself:

if (/[a-zA-Z]/.test(num)) {
  alert('Letter Found')
}
6
votes

There is no jquery needed:

var matchedPosition = str.search(/[a-z]/i);
if(matchedPosition != -1) {
    alert('found');
}
2
votes

I'm surprised that the answers here got so many upvotes when none of them really answer the question. Here's how to make sure that ONLY LATIN characters are in a given string.

const hasOnlyLetters = !!value.match(/^[a-z]*$/i);

The !! takes transforms something that's not boolean into a boolean value. (It's exactly the same as applying a ! twice, and in fact you can use as many ! as you'd like to toggle the truthiness multiple times.)

As for the RegEx, here's the breakdown.

  • /.../i The delimiter is a / and the i means to assess the statement in a case-insensitive fashion.
  • ^...$ The ^ means to look at the very beginning of a string. The $ means to look at the end of the string, and when used together, it means to consider the entire string. You can add more to the RegEx outside of these boundaries for things like appending/prepending a required suffix or prefix.
  • [a-z]*This part says to look for all lowercase letters. (The case-insensitive modifier means that we don't need to look at uppercase letters, too.) The * at the end says that we should match whats in the brackets any number of times. That way "abc" will match instead of just "a" or "b", and so forth.
1
votes

All these answers are correct, but I had to also check if the string contains other characters and Hebrew letters so I simply used:

if (!str.match(/^[\d]+$/)) {
    //contains other characters as well
}