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

4

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 πŸ˜ƒ.


Heroku

Deliver your unique apps, your own way.

Heroku tackles the toil β€” patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

Learn More

Top comments (0)

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay