Ali Habibzadeh
Ali Habibzadeh

Reputation: 11577

How to check if a string is not consist of any characters but those specified

I am trying to ensure that a string doesn't have anything but "A" or "B" or "C".

I thought it would be something like:

var str = "CBA";

str.match("[ABC]+");

but this is true also for "CBG". How can I make sure outside of "ABC" not to be allowed?

Upvotes: 2

Views: 69

Answers (1)

Sabuj Hassan
Sabuj Hassan

Reputation: 39443

You are missing the anchors(^ $). Here it is:

 str.match("^[ABC]+$");

These anchors will force the regex to match with whole string. Whereas without those, it matches with the part of the string.

Upvotes: 3

Related Questions