0

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?

Mr. Jo
  • 4,946
  • 6
  • 41
  • 100

4 Answers4

5

Why your example doesn't work:

Your regex looks for green or green,, however in your first example, the URL contains ,green. Being that you only replace the green portion of it, the result is a trailing comma: red,blue,.

It removed the c from the color which is totally strange.

I see nothing in your example that would demonstrate this behavior. I'd assume this is unrelated to the code you've provided.

var name = 'Green';
var re = new RegExp('(' + name + ',|' + name + ')');
var newUrl = "http://localhost.com/?color=Red,Blue,Green".replace(re, '');
console.log(newUrl);

As it seems Bruno has already covered the Regex solution, I'll leave you with a few alternatives.

Using URLSearchParams

You could fetch the param using URLSearchParams, split() the values into an array, filter() out green, and join() them back together.

const urlParams = new URLSearchParams(window.location.search);
const colors = urlParams.get('color');

let result = colors.split(",").filter(n => n != "green").join(",");

If you need to support Internet Explorer, you can reference this answer that includes the following method to retrieve the URL parameters - the result portion can remain the same:

function getParameterByName(name, url) {
  if (!url) url = window.location.href;
  name = name.replace(/[\[\]]/g, '\\$&');
  var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
    results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

var colors = gerParameterByName("color"); 
var result = colors.split(",").filter(n => n != "green").join(",");
Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
0

Just changing your code slightly would do it, but you should probably use Tyler's strategy to manipulate as an array instead

function replaceColor(search, name) {
  var reS = new RegExp(`=${name}(,|$)`);
  var reM = new RegExp(`,${name},`);
  var reE = new RegExp(`[=,]${name}$`);
  return search
    .replace(reS, '=')
    .replace(reM, ',')
    .replace(reE, '')
    .replace(/,$/, '')
}

var name = 'Green';
var newUrl = replaceColor(window.location.search, name);
window.history.pushState(null, null, newUrl);

Example:

function replaceColor(search, name) {
  var reS = new RegExp(`=${name}(,|$)`);
  var reM = new RegExp(`,${name},`);
  var reE = new RegExp(`[=,]${name}$`);
  return search
    .replace(reS, '=')
    .replace(reM, ',')
    .replace(reE, '')
    .replace(/,$/, '')
}

console.log(replaceColor('?color=Red,Green,Blue', 'Red'))
console.log(replaceColor('?color=Red,Green,Blue', 'Green'))
console.log(replaceColor('?color=Red,Green,Blue', 'Blue'))

console.log(replaceColor('?color=Red,DarkGreen,Blue', 'Green'))
console.log(replaceColor('?color=DarkGreen', 'Green'))
console.log(replaceColor('?color=Green', 'Green'))
BrunoLM
  • 97,872
  • 84
  • 296
  • 452
  • There seems to be a problem with ä, ü, ö, ß in german language. So for example when you set the first parameter to `groß` it's not working – Mr. Jo Dec 08 '18 at 04:08
  • 1
    @Mr.Jo I could not reproduce what you mentioned. There's nothing in this code that would cause an issue with any language (as long as they all use the same character `,` to separate words). Maybe try to isolate the issue and post a new question. – BrunoLM Dec 08 '18 at 04:20
  • Hey, I've updated my question so you can see the issue. When I run your answer this thing don't works on my browser side: console.log(replaceColor('?color=Red,Green,Blue', 'Blue')) – Mr. Jo Dec 08 '18 at 12:42
  • Sir are you still there? – Mr. Jo Dec 08 '18 at 19:03
0

This finally made it:

var reA = new RegExp('Value you want to remove');
var reB = new RegExp('(,&)');
var reC = new RegExp('(,,)');
var reD = new RegExp('(=,)');
var reE = new RegExp('(,$)');
window.history.pushState(null, null, decodeURIComponent(window.location.search).replace(reA, '').replace(reB, '&').replace(reC, ',').replace(reD, '=').replace(reE, ''));

Just enter the value you want to remove or pass a variable here with the value. Should work. For me it does.

Mr. Jo
  • 4,946
  • 6
  • 41
  • 100
-1

Add more condition into your regex

var re = new RegExp('(' + name + ',|' + name + '|,' + name + ')');
TaiNS
  • 99
  • 4