You need to understand why a regular expression does not replace all matches.

I am trying to figure out the following regex expression and why it gives me the result I get.

I have the following javascript:

let result = '7979797'.replace(/797/g,'77'); 

I would expect the result to have a value of 7777, but instead it has a value of 77977.

I was hoping someone could explain why I get the value 77977, and that I will need to change to regex so that it replaces all lines that have from 797 to 77.

+5
source share
2 answers

When a regular expression replaces the first 797 with 77 , it does not re-look at the material that it replaced ( 77 ), so it sees 9 next, then 797 , which leads to the result.

+12
source

Alternatively, we can use the code below to achieve the desired effect.

 var input = '7979797'; var reg = /797/; while(reg.test(input)){ input = input.replace(reg,'77') } console.log(input) 
+3
source

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


All Articles