Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to understand why the regex is not replacing all matches

I am trying to figure out the following regex expression and why it is giving me the result I am getting.

I have the following javascript:

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

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

I was hoping someone could explain why I am getting a value of 77977 and what I would need to change to the regex to get it replace all strings that have the patter 797 to 77.

like image 987
Mark Pearl Avatar asked Jan 01 '16 07:01

Mark Pearl


1 Answers

When a regex replaces the first 797 with 77, it doesn't rescan the material it has replaced (the 77), so it sees 9 next, then 797, leading to the result you get.

like image 140
Jonathan Leffler Avatar answered Oct 04 '22 04:10

Jonathan Leffler