So I tried this:
if (/^[a-zA-Z]/.test(word)) { // code }
It doesn't accept this : " "
But it does accept this: "word word"
, which does contain a space :/
Is there a good way to do this?
We can use the regex ^[a-zA-Z]*$ to check a string for alphabets. This can be done using the matches() method of the String class, which tells whether the string matches the given regex.
Use the test() method on the following regular expression to check if a string contains only letters and numbers - /^[A-Za-z0-9]*$/ . The test method will return true if the regular expression is matched in the string and false otherwise. Copied!
To check if a character is a letter, call the test() method on the following regular expression - /^[a-zA-Z]+$/ . If the character is a letter, the test method will return true , otherwise false will be returned. Copied!
With /^[a-zA-Z]/
you only check the first character:
^
: Assert position at the beginning of the string[a-zA-Z]
: Match a single character present in the list below: a-z
: A character in the range between "a" and "z"A-Z
: A character in the range between "A" and "Z"If you want to check if all characters are letters, use this instead:
/^[a-zA-Z]+$/.test(str);
^
: Assert position at the beginning of the string[a-zA-Z]
: Match a single character present in the list below: +
: Between one and unlimited times, as many as possible, giving back as needed (greedy)a-z
: A character in the range between "a" and "z"A-Z
: A character in the range between "A" and "Z"$
: Assert position at the end of the string (or before the line break at the end of the string, if any)Or, using the case-insensitive flag i
, you could simplify it to
/^[a-z]+$/i.test(str);
Or, since you only want to test
, and not match
, you could check for the opposite, and negate it:
!/[^a-z]/i.test(str);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With