I have requirement for a regex that does not match strings after specific string, suppose I have the following string
4515856581128483548598852649285965451533568536158523
In the above string, I have to replace all the 5s with 0 except the 5s immediate after to 8, as below:
4010856081128483048598852649285960401033068536108523
I have tried, as below:
"4515856581128483548598852649285965451533568536158523".replace(/5(?!8)/g,'0')
"4015806581128483048098802649280960401033068036158023"
It replaced all 5's except followed by 8, so I tried:
"4515856581128483548598852649285965451533568536158523".replace(/(?!8)5/g,'0')
"4010806081128483048098802649280960401033068036108023"
It replaced all 5's. How can I replace all the 5s with 0 except the 5's immediate after to 8?
You can use below regex
.replace(/(85)|5/g, (m, $1) => $1 || '0')
The regex will search for 85 or 5. If 5 followed by 8 is found, no replacement happens. When there is no 85, the matched 5 will be replaced by 0.
Note that $1 here is the value of first captured group i.e. 85 when matched. If 85 is not found, $1 will be empty string and thus the OR condition will return second value i.e. '0'.
console.log('4515856581128483548598852649285965451533568536158523'.replace(/(85)|5/g, (m, $1) => $1 || '0'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With