Check if string contains only letters in javascript

JavascriptRegex

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

The fastest way is to check if there is a non letter:

if (!/[^a-zA-Z]/.test(word))

Solution 3 - Javascript

You need

/^[a-zA-Z]+$/

Currently, you are matching a single character at the start of the input. If your goal is to match letter characters (one or more) from start to finish, then you need to repeat the a-z character match (using +) and specify that you want to match all the way to the end (via $)

Solution 4 - Javascript

Try this

var Regex='/^[^a-zA-Z]*$/';

 if(Regex.test(word))
 {
 //...
 }

I think it will be working for you.

Solution 5 - Javascript

try to add \S at your pattern

>^[A-Za-z]\S*$

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDennisvBView Question on Stackoverflow
Solution 1 - JavascriptOriolView Answer on Stackoverflow
Solution 2 - JavascriptCasimir et HippolyteView Answer on Stackoverflow
Solution 3 - JavascriptJDBView Answer on Stackoverflow
Solution 4 - JavascriptRajiView Answer on Stackoverflow
Solution 5 - JavascriptToninoView Answer on Stackoverflow