Alex2134
Alex2134

Reputation: 567

Removing value from a comma seperated list with Regex

I'm having difficulty using regex to remove a value from a comma seperated list; the value could be anywhere in the list, my current solution which doesn't seem to work is:

var val = "455";
    sList = sList
        .replace(new RegExp("\b"+val,""))
        .replace(new RegExp("\b"+val+",(.+)"),"$1")
        .replace(new RegExp("\b(.+),"+val),"$1")
        .replace(new RegExp("(.*),"+val+",(.+)"),"$1,$2");

List could be:

var sList ="455" || "val1,val2,455,val4,valn" || "455,val2,val3,valn" || "val1,val2,val3,455";

Could anyone advise?

Many thanks, Alex

Upvotes: 2

Views: 207

Answers (2)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

As JNYRanger suggests it, it is more simple to split your string with commas, to remove the value and then to join the resulting array with comma:

var str= "val1,val2,455,val4,valn";

str = str.split(',').filter(function (i) { return i !== '455' }).join(',');

To do it with regex, you can simply list all possibilities like this:

/^455(?:,|$)|,455(?=,|$)/

Example:

var re = new RegExp("^" + val + "(?:,|$)|," + val + "(?=,|$)");

str = str.replace(re, '');

Upvotes: 2

bjfletcher
bjfletcher

Reputation: 11508

Some people like to use split and join:

var keep = [];
"val1,val2,455,val4,valn".split(",").forEach(function(val) {
  if (val !== "455") keep.push(val);
});
keep.join(",");

will yield:

"val1,val2,val4,valn"

Others, like me, would prefer to use regex's match instead, replacing split(",") above with match(/[^,]+/g).

Upvotes: 1

Related Questions