If you want to do this in just one regular expression, you could do this:
/&foo(=[^&]*)?|^foo(=[^&]*)?&?/
This is because you need to match either an ampersand before the foo=…, or one after, or neither, but not both.
To be honest, I think it’s better the way you did it: removing the trailing ampersand in a separate step.