19

I'm trying to create a regex that will match only when the string has anything but alphas, spaces, and hyphens. In other words, the string can only contain letters, spaces, and hyphens.

2 Answers 2

36

If you are looking for a test for validity:

// from string start to end, only contains '-' "whitespace" or 'a'-'z' 
someString.match(/^[-\sa-zA-Z]+$/) 

Or the negation:

// has some invalid character not '-' "whitespace" or 'a'-'z'
someString.match(/[^-\sa-zA-Z]/) 
Sign up to request clarification or add additional context in comments.

Comments

-2
if(someString.match(/[a-z -]+/i){
    // it's valid
}

3 Comments

"the string can only contain letters, spaces, and hyphens."
change regexp to this: /[^a-z \-]+/i
If you don't anchor your expression with ^ and $, this will simply match a substring. The rest of the string can still contain unwanted characters.

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.