2

I have this bit of Javascript,

if (/[A-Za-z0-9-]+/.test(sZip)) {
   alert(Match!);
}

and I'm using this as my test case "1234;"

I don't want "1234;" to be a match, I want only for example "1234" or "12 34" or "12-34" to match.

3
  • Match! should be contained within quotes. Commented Oct 4, 2011 at 9:38
  • Just a short clarification: Should ';1234' be a match? Commented Oct 4, 2011 at 9:56
  • @exiva, if you want to match everything, then "12 34" should not be matched since it contains a space. Or did you forget to include it in your character class? Commented Oct 4, 2011 at 9:59

4 Answers 4

5
/[A-Za-z0-9-]+$/

(The $ is the key: it means end of string, no more characters)

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

2 Comments

Sorry, I previously made a comment recommending to add the ^, but it looks like this should probably not be done (see my comment beneath Boldewyn's answer).
Hmm true that, removed again :)
3

Start the regular expression with ^ and end it with $. This way you tell it to match the whole string against the pattern. MDN docs.

If you want the space matched, you need to include it in the brackets. For space and dash to delimit alphanum fields, take this approach:

/^([A-Za-z0-9]+[ -])*[A-Za-z0-9]+$/
---^ 0 or more "ABC123-" fields
---------------^ separated by either dash or space
---------------------^ but at least once a "ABC123" field (no dash)

2 Comments

Hmm, I don't think the OP wants the ^ since he want "12 34" to be matched, which contains a space that is not contained in his char-set [A-Za-z0-9-].
Let's ask him. I got the need for ^ from the question title.
2
    if (/[A-Za-z0-9-]+$/.test(sZip)) { 
      alert(Match!); 
    }  

Comments

0

This should work:

if (/[A-Za-z0-9-]+\s/.test(sZip)) {
   alert(Match!);
}

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.