I am seeing a weird behaviour when executing the same regexp matching several times:
var r = /(.*)/g
var d = "a"
console.log(r.exec(d))
console.log(r.exec(d))
This produces:
["a", "a"]
["", ""]
Why is it not matching anything the second time around?
That is what the
gflag does. When you use it, exec will continue the next search from the end the previous match. But after your first match (a) there is nothing more left in the string, so you get an empty match. This empty match is usually used to terminate anexec-loop. If you know that there is only one match, remove theg(it means “global” search).Note that you can (and should) get rid of those parentheses. They just cost you performance. Without them you will only get one
ain the resulting array.If you do want to consider multiple matches, but disregard that last empty match, use the loop technique:
Note that you only need this loop if you actually have (meaningful) capturing groups. If not (if you only want to get full matches), you can use
matchinstead as elclanrs points out:EDIT:
I just realised, most of what I said is partially true but not the actual cause of
["", ""]. What really happens is this: the first time.*matchesa. The second time the engine tries to continue the search after the previous match (aftera). Since your pattern has.*(which mean 0 or more characters) it will now continue to match empty strings (because they match the pattern). And matching an empty string also does not advance the position for the next search. Hence, even with.matchyou will get["a", ""](matchis clever enough to abort in such a case).In fact, if you use that regex with the loop-technique you will get an endless loop (because
match = ["", ""]will obviously not cause the loop to terminate). But in any case, you should realise that your pattern is nonsensical due to the*. It can match anything (including nothing). At least use.+. For whatever purpose.