Since you’re using global flag in exec call regex engine remembers lastIndex which is is a read/write integer property of regular expressions that specifies the index at which to start the next match.
Place this to reset it:
Just before next call to RegExp.exec
re.lastIndex = 0 allows you to reset the search index to perform a second search starting from the beginning. Without it, the search begins at the index of the last match, which would yield
null in this case.
Read this Mozilla doc for more info on this. As per this manual:
This property is set only if the regular expression used the “g” flag to indicate a global search.