PHP Noob
PHP Noob

Reputation: 1615

How to check if string contains Latin characters only?

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

Example:

var str = '123z56';

Upvotes: 68

Views: 130785

Answers (6)

Rick Mac Gillis
Rick Mac Gillis

Reputation: 873

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.

Upvotes: 16

Jake Neumann
Jake Neumann

Reputation: 380

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
}

Upvotes: 1

jondavidjohn
jondavidjohn

Reputation: 62392

No jQuery Needed

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

Upvotes: 120

Blender
Blender

Reputation: 298106

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());

Upvotes: 48

SomeoneYouDontKnow
SomeoneYouDontKnow

Reputation: 1299

There is no jquery needed:

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

Upvotes: 5

PHP Noob
PHP Noob

Reputation: 1615

Ahh, found the answer myself:

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

Upvotes: 11

Related Questions