Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
92
rated 0 times [  98] [ 6]  / answers: 1 / hits: 153991  / 10 Years ago, mon, may 5, 2014, 12:00:00

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?


More From » regex

 Answers
22

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);

[#71175] Friday, May 2, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
madalynn

Total Points: 342
Total Questions: 95
Total Answers: 106

Location: Turkmenistan
Member since Sat, Apr 16, 2022
2 Years ago
;