Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string contains only letters in javascript

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?

like image 482
DennisvB Avatar asked May 05 '14 15:05

DennisvB


People also ask

How do you check if a string has only letters?

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.

How do you check if a string contains only letters and numbers in JavaScript?

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!

Is alphabet function in JavaScript?

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!


1 Answers

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); 
like image 177
Oriol Avatar answered Sep 20 '22 07:09

Oriol