I've this URL here:
http://localhost.com/?color=Red,Blue,Green
The URL can also have this format:
http://localhost.com/?color=Red,Green,Blue
I'm trying now to remove the value Green
from the URL including the ,
if it acts as separator. I've tried this RegExp here:
var name = 'Green';
var re = new RegExp('(' + name + ',|' + name + ')');
var newUrl = window.location.search.replace(re, '');
window.history.pushState(null, null, newUrl);
So what I want to say is, remove Green,
or Green
so if the Green,
can't be found, the second check will be used. But when I run this the URL looks like this:
http://localhost.com/?olor=Red,Green,Blue
It removed the c
from the color which is totally strange. I've tested my RegExp
online in an tool and the texts were selected but here it don't works. What I'm doing wrong again?
Update
This is a try with Brunos answer but as you can see sometimes it don't woks:
function replaceColor(search, name) {
var reS = new RegExp(`=${name}(,|$)`);
var reM = new RegExp(`,${name},`);
var reE = new RegExp(`\b${name}$`);
return search
.replace(reS, '=')
.replace(reM, ',')
.replace(reE, '')
.replace(/,$/, '')
}
alert(replaceColor('?size=K,M,S&color=Green,Red,Black', 'Red')) //Works
alert(replaceColor('?size=K,M,S&color=Green,Red,Black', 'Green')) //Works
alert(replaceColor('?size=K,M,S&color=Green,Red,Black', 'Black')) //Don't works
How can I fix this?