This occurs because you are repeating the capturing group, and all language implementations preserve only the last capturing group. In other words, if there is a choice between capturing secondname
and secondname3?p=12
, Javascript will choose the last one even though both are equally valid. This answer explains the core of the problem.
The correct way to resolve such issues is to rewrite your regex group to make the parameter you want to retrieve unambiguous - usually this is done by changing occurrences of .*
(note it is the .
character here that is problematic) to something more appropriate, such as \w*
in this case. You want to avoid repeating capturing groups. I will explain why \w
does so.
Here \w
represents the word metacharacter - it matches a-z, A-Z and 0-9 and nothing else. In this particular case, the regex can no longer match against secondname3?p=12
because it contains an =
, which isn't allowed by \w
. Hence why @Avinash Raj's solution works - even though the capturing group is repeated, there is only one real instance of the whole thing matching.