Just use the delimiters ^
and $
, to mark the beginning and end of the string. So it does not take the zero of the 10
unintentionally:
var mes = "10";
var teste = /^([024679]|11)$/.test(mes);
console.log(teste);
I also put in parentheses to ensure that between the beginning and the end there is only one of the two options (the numbers 0, 2, 4, 6, 7 and 9, or the 11). Just to clarify the difference:
^[024679]|11$
(without parentheses): means that the string starts with [024679]
or ends with 11
$([024679]|11)$
(parentheses): means the string starts, then we have [024679]
or 11, and then there’s the end of the string.
The difference is subtle, because without parentheses the regex will accept "2000"
(as it begins with 2) or "111"
(ends in 11). For example:
console.log(/^[024679]|11$/.test("2000")); // true
console.log(/^[024679]|11$/.test("111")); // true
console.log(/^([024679]|11)$/.test("2000")); // false
console.log(/^([024679]|11)$/.test("111")); // false
Also, use the $
also ensures that the regex will not take the "2000"
:
console.log(/^([024679]|11)$/.test("2000")); // false
console.log(/^([024679]|11)/.test("2000")); // true
The above solution, of course, assumes that the string will only have the digits of the month, and nothing else. If she has other information, just change the delimiters (one option is to use \b
, for example):
var teste = /\b([024679]|11)\b/.test("abc 11 xyz");
console.log(teste); // true
teste = /\b([024679]|11)\b/.test("abc 10 xyz");
console.log(teste); // false
But then it depends on how the month will be in your strings.
Cool. I just tested with the
^
at the beginning and attended well, because will not catch the0
of10
. But the months are just the same: 0, 2, 4... and 11, that is, until October is only 1 digit, November and December that are 2: 10 and 11. Thanks!– Sam
@Sam I updated the answer, I saw that I had some cases that failed and I put a few more examples (including explaining why I think to use
$
is better) :-) Of course if your entries are validated and regex always gets a valid month value, you don’t need so much precious. But any way, the record :-)– hkotsubo
It’s just the gold! Thanks!
– Sam