Cody
Cody

Reputation: 2649

Javascript test method not working ( as expected )

Regular expression

 [A-Za-z_-]+ 

should match strings that only have upper and lower case letters, underscores, and a dash

but when I run in chrome console

 /[A-Za-z_-]+/.test("johmSmith12")

Why it returns true

Upvotes: 1

Views: 167

Answers (2)

ajp15243
ajp15243

Reputation: 7950

It is due to your regex looking for any sequence of characters within the test string that matches the regex. In your example, "johnSmith" matches your regex criteria, and so test returns true.

If you instead put ^ (start of string) and $ (end of string) at the ends of your regex, then you would assert that the entire string must match your regex:

/^[A-Za-z_-]+$/.test("johnSmith12");

This will return false.

Upvotes: 0

Qtax
Qtax

Reputation: 33918

Because you didn't anchor the expression. You need to add ^ and $, which match beginning and end of string.

For example:

^[A-Za-z_-]+$

Just the [A-Za-z_-]+ will match johnSmith in your example, leaving out the 12 (as David Starkey pointed out).

Upvotes: 2

Related Questions