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 froma-z
and also the capital letters fromA-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
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!";
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]/;
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
- The method returns boolean
true
if present andfalse
if not.
See the example live in JSBin.