0

I found a way to check if a string has only one space between whatever characters.

if (/^[^ ]* [^ ]*$/.test(name))

But I want the string to contain only alpha characters between one space. I'm new to regex so I'm not sure how to do this.

I tried this but it doesn't seem to work:

if (/^[a-z ]* [a-z ]*$/i.test(name))

"John Smith" should work but something like "John W Smith" or "111 111" should not work.

2
  • 1
    I found regexr.com to be very helpful in writing regexes Commented Oct 2, 2020 at 14:30
  • Try: /[a-z]*\s[a-z]*$/ - removed some spaces. Commented Oct 2, 2020 at 15:25

1 Answer 1

2
/^[a-zA-Z]* [a-zA-Z]*$/

where [a-zA-Z]* matches 0 or more (*) alphabetic characters (a-z) case insensitively (a-zA-Z). Mind that the only space is between the two capturing groups, because it needs to be matched literally. I would really recommend using https://regex101.com/ for testing your regular expressions, it saved me a lot of time.

Sign up to request clarification or add additional context in comments.

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.