2

I have a long string

Full_str1 = 'ab@xyz.com;cab@xyz.com;c-ab@xyz.com;c.ab@xyz.com;c_ab@xyz.com;';
removable_str2 = 'ab@xyz.com;';

I need to have a replaced string which will have resultant Final string should look like,

cab@xyz.com;c-ab@xyz.com;c.ab@xyz.com;c_ab@xyz.com;

I tried with

str3 = Full_str1.replace(new RegExp('(^|\\b)' +removable_str2, 'g'),"");

but it resulted in

cab@xyz.com;c-c.c_ab@xyz.com;
Him Singhvi
  • 103
  • 3
  • 13

3 Answers3

2

Here a soluce using two separated regex for each case :

  • the str to remove is at the start of the string
  • the str to remove is inside or at the end of the string

PS : I couldn't perform it in one regex, because it would remove an extra ; in case of matching the string to remove inside of the global string.

const originalStr = 'ab@xyz.com;cab@xyz.com;c-ab@xyz.com;c.ab@xyz.com;ab@xyz.com;c_ab@xyz.com;';
const toRemove = 'ab@xyz.com;';

const epuredStr = originalStr
                      .replace(new RegExp(`^${toRemove}`, 'g'), '')
                      .replace(new RegExp(`;${toRemove}`, 'g'), ';');

console.log(epuredStr);
Orelsanpls
  • 22,456
  • 6
  • 42
  • 69
1

First, the dynamic part must be escaped, else, . will match any char but a line break char, and will match ab@xyz§com;, too.

Next, you need to match this only at the start of the string or after ;. So, you may use

var Full_str1 = 'ab@xyz.com;cab@xyz.com;c-ab@xyz.com;c.ab@xyz.com;c_ab@xyz.com;';
var removable_str2 = 'ab@xyz.com;';
var rx = new RegExp("(^|;)" + removable_str2.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), "g");
console.log(Full_str1.replace(rx, "$1"));
// => cab@xyz.com;c-ab@xyz.com;c.ab@xyz.com;c_ab@xyz.com;

Replace "g" with "gi" for case insensitive matching.

See the regex demo. Note that (^|;) matches and captures into Group 1 start of string location (empty string) or ; and $1 in the replacement pattern restores this char in the result.

NOTE: If the pattern is known beforehand and you only want to handle ab@xyz.com; pattern, use a regex literal without escaping, Full_str1.replace(/(^|;)ab@xyz\.com;/g, "$1").

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

i don't find any particular description why you haven't tried like this it will give you desired result cab@xyz.com;c-ab@xyz.com;c.ab@xyz.com;c_ab@xyz.com;

const full_str1 = 'ab@xyz.com;cab@xyz.com;c-ab@xyz.com;c.ab@xyz.com;c_ab@xyz.com;';
const removable_str2 = 'ab@xyz.com;';

const result= full_str1.replace(removable_str2 , "");

console.log(result);
ArunPratap
  • 4,816
  • 7
  • 25
  • 43