0

I am using regex to verify that a string only contains alphabets and spaces. Regex is defined as

var regex = /^[A-Za-z ]/;

but even if I am testing it with a string "X," , it is giving a true result.

What is the error here?

1
  • Your regex only means: the string must start with a letter or a space, but nothing else. Try this one: /^[A-Za-z ]*$/. Commented Sep 6, 2012 at 11:30

4 Answers 4

1

^[A-Za-z ] only matches one character. and ^ means the start of the string. To accomplish what you want, use:

+ - This means match one or more. Alternatively you can use:

* - Which means match zero or more.

But I think you're better off with the first one (+). Another thing is, match for the whole string. This means you have to search from the first to the last character.

$ - This means match the end.

Your code should be like this:

var regex = /^[A-Za-z ]+$/;
Sign up to request clarification or add additional context in comments.

Comments

0

Your regex matches the first letter of your input and therefore true is returned.. You need to add $ to make sure you only match a complete string from the beginning (^) to the end ($).

var regex = /^[A-Za-z ]*$/;

Comments

0

Try using this:

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

Comments

0

This is the correct way:

/^[A-Za-z ]*$/

Regex Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.