Replacing only part of regular expression matching

consider the following javascript code:

"myObject.myMethod();".replace(/\.\w+\(/g, "xxx"); 

it gives " myObjectxxx); " because " .myMethod( " is selected.

Now I would select only myMethod . In other words, I want to select any word starting with . and ending with ( (excluded).

Thanks, Luke.

+6
source share
3 answers

General answer: write down the part you want to keep in parentheses, and include it in the substitution string as $1 .

See the regexp lookup guide for more details.

Here: just turn it on . and ( to the substitution string.

For the exercise, write a regular expression that will turn any line of the circuit --ABC--DEF-- into --DEF--ABC-- for arbitrary alphabetic values ABC and DEF . So, --XY--IJK-- should turn into --IJK--XY-- . Here you really need to use capture groups and backlinks.

+18
source

You can use lookaround statements:

 .replace(/(?<=\.)\w+(?=\()/g, 'xxx') 

This will allow the coincidence to succeed, while not being part of the match itself. Thus, you replace only the part between them.

A simpler option for people unfamiliar with regular expressions probably just includes . and ( in replacement:

 .replace(/\.\w+\(/g, ".xxx(") 
+3
source

I would suggest a slightly different approach:

 "myObject.myMethod();".replace(/^([^\.]*\.)\w+(\(.*)$/g, "$1xxx$2"); 

although simpler solutions have been proposed.

+1
source

Source: https://habr.com/ru/post/906798/


All Articles