Search code examples
javascriptregexstringreplaceregexp-replace

Unable to replace using RegExp


I am trying to replace a particular set of strings using RegExp but it is not replacing. The regex I am trying is

\@223(?:\D|'')\gm

The set of strings to test on are these

@223 ->Replace 223 with #
@223+@33 ->Replace 223 with #
@22;    ->Not Replace
@2234   ->Not Replace 
@22234  ->Not Replace
@223@44  ->Replace 223 with #

Solution

  • if this what you went :

    var string = `
    @223
    @223+@33
    @22;
    @2234
    @22234
    @223@44
    `;
    regex = /(?<=@)(223)(?=\D)/g;
    string = string.replace(regex, "#");
    console.log(string);
    

    output :

    @#
    @#+@33
    @22;
    @2234
    @22234
    @#@44
    

    explanation :

    (?<=@) : test if leaded by @ character.
    (?=\D) : followed by any character except digit