2

I have a long string

Full_str1 = '[email protected];[email protected];[email protected];[email protected];[email protected];';
removable_str2 = '[email protected];';

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

[email protected];[email protected];[email protected];[email protected];

I tried with

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

but it resulted in

[email protected];[email protected];
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 = '[email protected];[email protected];[email protected];[email protected];[email protected];[email protected];';
const toRemove = '[email protected];';

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 = '[email protected];[email protected];[email protected];[email protected];[email protected];';
var removable_str2 = '[email protected];';
var rx = new RegExp("(^|;)" + removable_str2.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), "g");
console.log(Full_str1.replace(rx, "$1"));
// => [email protected];[email protected];[email protected];[email protected];

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 [email protected]; 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 [email protected];[email protected];[email protected];[email protected];

const full_str1 = '[email protected];[email protected];[email protected];[email protected];[email protected];';
const removable_str2 = '[email protected];';

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

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