DennisvB
DennisvB

Reputation: 1018

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?

Upvotes: 82

Views: 170534

Answers (6)

Shubham Verma
Shubham Verma

Reputation: 9913

Here is the code to check the string:

/**
 * Check null, should contain only letters, allowed space, min length is minLength. 
 * @param minLength 
 * @param string 
 * @returns 
 */
export const isStringInValid = (string: string, minLength: number) => {
    return !string || !string?.trim() || !/^[a-zA-Z ]+$/.test(string) || string.length < minLength
}

Upvotes: 0

Raji
Raji

Reputation: 41

Try this

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

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

I think it will be working for you.

Upvotes: 3

Oriol
Oriol

Reputation: 287960

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

Upvotes: 158

Tonino
Tonino

Reputation: 1166

try to add \S at your pattern

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

Upvotes: 0

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89547

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

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

Upvotes: 22

JDB
JDB

Reputation: 25820

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

Upvotes: 13

Related Questions