DEV Community

Cover image for How to check if a string contains at least one letter using regular expression (regex) in JavaScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to check if a string contains at least one letter using regular expression (regex) in JavaScript?

Originally posted here!

To check if a string contains at least one letter using regex, you can use the [a-zA-Z] regular expression sequence in JavaScript.

  • The [a-zA-Z] sequence is to match all the small letters from a-z and also the capital letters from A-Z. This should be inside a square bracket to define it as a range.
// Check if string contain atleast one letter ๐Ÿ”ฅ
/[a-zA-Z]/.test("12345hello6789!"); // true
Enter fullscreen mode Exit fullscreen mode

To get a more in-depth explanation of the process. Read on ๐Ÿ“–.

Consider we have a string with some letters 12345hello6789! like this,

// String with some letters
const str = "12345hello6789!";
Enter fullscreen mode Exit fullscreen mode

Now let's write the regex by wrapping the [a-zA-Z] sequence range inside regular expression delimiters like this /[a-zA-Z]/.

// String with some letters
const str = "12345hello6789!";

// Regular expression
const regex = /[a-zA-Z]/;
Enter fullscreen mode Exit fullscreen mode

At last, we can use the test() method in the regular expression and pass the string as an argument to the method to test if the string contains at least one letter. It can be done like this,

// String with some letters
const str = "12345hello6789!";

// Regular expression
const regex = /[a-zA-Z]/;

// Check if string contians letters
const doesItHaveLetter = regex.test(str);

console.log(doesItHaveLetter); // true
Enter fullscreen mode Exit fullscreen mode
  • The method returns boolean true if present and false if not.

See the example live in JSBin.

Feel free to share if you found this useful ๐Ÿ˜ƒ.


Top comments (0)