I would like to parse url query params intelligently using regex.
Things I've had to consider: 1) params can be out of order 2) only certain params must match
Given a query string: "?param1=test1¶m2=test2&parm3=test3" I would like to run javascript regex to parse param1's value and param3's value.
The regex I've come up with so far is:
/(?:[?&](?:param1=([^&]*)|param3=([^&]*)|[^&]*))+$/g
This regex seems to work fine for me in sites like https://regex101.com/.
However, when I run the JS method below, I always get undefined for $2, which is what param1's value should be parsing to. Any help or suggestion?
"?param1=test1¶m2=test2¶m3=test3".replace(
/(?:[?&](?:param1=([^&]*)|param3=([^&]*)|[^&]*))+$/g,
function ($0, $1, $2, $3) { return $0 + ' ' + $1 + ' ' + $2 + ' ' + $3; });
This returns $2 as undefined and $3 as test3. However, if I exclude both param2 and param3 from the url query string, I am successfully able to parse param1 as $2. A bit confused about that.
thanks!