Search code examples
javascriptregexreplacereplaceall

Need to replace a string from a long string in javascript


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;

Solution

  • 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);