Since your regular expression is already designed to match all mac addresses in a string (instead of just one at a time), you can fix this bug by removing the g
flag. Also, to prevent matching only part of the string, you need to include the ^
and $
characters at the beginning and end of your regular expression.
var re = /^(([A-Fa-f0-9]{2}[:]){5}[A-Fa-f0-9]{2}[,]?)+$/
Because you are using a global regular expression (due to the g
at the end), the regular expressions keeps state about its last match, which will affect future matches.
Specifically, the RegExp object you store in the re
variable has a lastIndex
that is updated to point to the first character after each match. Future matches are performed starting at that index, even if you match against a new string. Once a match is unsuccessful, lastIndex
is reset to 0
.
Graphically, this is what matches and where re.lastIndex
points after each match:
t1: 11:22:33:44:55:66 ^ t2: 11:22:33:44:55:66,12:22:33:44:55:66 ^ t3: 11:22:33:44:55:66,11asdfasdf:22:33:44:55:66 No match! ^ Since there was no match, lastIndex is reset to 0. t4: 11:22:33:44:55:66,haha ^ t5: 11:22:33:44:55:66, No match! ^ t6: 123123123123 No match! ^ t7: 11:22:33:44:55:66,33:44:55:66:77:88: ^ t8: 11:22:33:44:55:66,33:44:55:66:77:88asdfasdfasdfasdfasdfasd No match! ^ t9: 11:22:33:44:55:66,dfasdfasdfasdfasdfasd ^ t10: 11:22:33:44:55:66,12:22:33:44:55:66,12:33:44:55:66:77 ^ t11: 11:22:33:44:55:66,12:22:33:44:55:66,wahaa No match! ^