How to remove word with extra delimiter from given string?

Viewed 91

I have following string.

var str = "abc, abcd, abc, abcf, abc, abc";

I want to remove abc from a given string with , (space). Basically, I want output something like below.

var output = "abcd, abcf";

Note:- If possible give regex solution(with one replace only).

Things I have tried:-

1) 1st approach

var str = "abc, abcd, abc, abcf, abc, abc";
var w = "abc";
var output = str.split(", ").filter(x => !(x === w)).join(", ");
console.log(output);

Here I have used split, then filter and then join, basically 3 array operations. (which I think not good when performance is concerned).

2) 2nd approach

var str = "abc, abcd, abc, abcf, abc, abc";
var w = "abc";
var regex = new RegExp("\\b" + w + "\\b", "ig");
var output = str.replace(regex,"");
output = output.replace(/, , /ig,", ");
output = output.replace(/^, |, $/ig,"");
console.log(output);

Here I am using three times replace.

Is it possible achieve in simpler way?

3 Answers

You may use this .replace code:

var w = 'abc';

var str = "abc, abcd, abc, abcf, abc, abc";

str = str.replace(new RegExp("\\b" + w + "(?:, |$)", "g"), '')
         .replace(/, $/, '');

console.log(str);
//=> "abcd, abcf"

  • In the first .replace call we are replacing word abc with the trailing ", ".
  • We effectively use this regex first: /\babc(?:, |$)/
  • In the second .replace call we remove any remaining trailing ", " in the string.
  • We effectively use this regex second time: /, $/ to remove any left over ", "

Performance Test Link

Using one replace()

var str = "abc, abcd, abc, abcf, abc, abc";

var rep = "abc";

var r = new RegExp("(, "+rep+"(?![a-z]))|("+rep+"(?![a-z]), )","g");
 
str = str.replace(r, "");

console.log(str);

There is two more way of doing above.

1) Using single .replace()

var str = "abc, abcd, abc, abcf, abc, abc";
var w = "abc";
var regex = new RegExp(", " + w + "\\b", "g");
var output = (", " + str).replace(regex,"").substr(2);
console.log(output);

2) Using .reduce()

var str = "abc, abcd, abc, abcf, abc, abc";
var w = "abc";
var output = str.split(", ").reduce((a, x, i) => {
                    if(x !== w){
                      a = a + ", "+ x;
                    }
                    return a;
                  },'').substr(2);
console.log(output);

Related