0

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 #
3
  • do you went to change it to 223 with # if it start with @223 ? Commented Oct 30, 2020 at 5:43
  • do you want replace 233 by # ? Commented Oct 30, 2020 at 5:43
  • Just use str = str.replace(/@223\b/, "#") Commented Oct 30, 2020 at 6:35

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

There are two issues with your regex:

  1. You're using the wrong slashes, should be /@223(?:\D|'')/gm.
  2. The non-capturing group will still be included in the complete match, so you might need to add parenthesis around just the @223 part and just replace that group.

You can test your regex in a service like regex101.com. Note that in that service, the start and end slashes are already implicitly included.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.