Question

I want to remove some parameters of my url www.domain.com?a=1&b=2&c=3

For example I have this code already from stackoverflow here which works fine:

return location.href=location.href.replace(/&?a=([^&]$|[^&]*)/i, "");

As I am not familiar with regex, how is it possible to add another parameter to this line? Right now it only removes the "a" parameter. I also want the "b" parameter to be removed too.

Edit: Ofcorse I am not using "a" and "b" as a parameter. How does it work with parameters like "crop-image" and "subscription" so the domain looks like: www.domain.com?crop-image=1&subscription=1&keep=me

Was it helpful?

Solution

Replace [ab] with a set of capture groups of the parameters you want to remove.

location.href=location.href.replace(/&?((crop-image)|(subscription))=([^&]$|[^&]*)/gi, "");

Whatever is contained inside each group will match exactly against a full parameter name. You can or (|) together as many groups as you need.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top