Mark Pearl
Mark Pearl

Reputation: 7653

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.

Upvotes: 5

Views: 169

Answers (2)

Jagdish Idhate
Jagdish Idhate

Reputation: 7742

As a alternative we can use below code to achieve desired effect.

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

Upvotes: 3

Jonathan Leffler
Jonathan Leffler

Reputation: 753525

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.

Upvotes: 12

Related Questions