This should do the trick for you:
location.href=location.href.replace(/&?[ab]=([^&]$|[^&]*)/gi, "");
[ab]
so that it will match one of either a
or b
. The g
flag is added to make it global so that it will match multiple instances.
Fiddle
var href = "www.domain.com?f=4&a=1&foo=bar&b=2&c=3";
href=href.replace(/&?[ab]=([^&]$|[^&]*)/gi, "");
console.log(href); // www.domain.com?f=4&foo=bar&c=3
Also, this part is not necessary ([^&]$|[^&]*)
, it could be simply [^&]*
to make this regex:
/&?[ab]=[^&]*/gi
Due to your edit (longer attribute names), this would work for you. Note that the "or" at the end is still not required as it serves no purpose in this case.
Fiddle
var href = "www.domain.com?ab=4&c=5&ba=2&f=10";
href=href.replace(/&?((ab)|(ba))=[^&]*/gi, "");
console.log(href); //www.domain.com?&c=5&f=10
Notice that this will leave an &
at the beginning if the first attribute is removed? This shouldn't cause any issues but if you would still like to fix that, you could do this:
href=href.replace(/&?((ab)|(ba))=[^&]*/gi, "").replace(/\?&/,"?");
With this you will end up with www.domain.com?c=5&f=10
instead of www.domain.com?&c=5&f=10
. While it is possible to do it within a single regex, especially in javascript without lookbehinds it's much easier and more compact (less repetitive) to do it in a separate regex like I did above.