How to check if a string contains [a-zA-Z]
characters only?
Example:
var str = '123z56';
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.