Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace two patterns at the same regex in JavaScript

I need to replace one or two letters in a string in javascript but the letter is the same, then if I replace one of the two appareances the format is not correct:

HH:mm z [on] D MMM YYYY
HH:mm zz [on] D MMM YYYY

In the first case in example z should be replaced by CEST and with zz by Central European Summer Time.

I tried with regex but it is possible to replace the exact occurrence of first pattern without affecting to the second pattern?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Not worth a regexp – just do two replaces or loop {zz:"Central European Summer Time",z:"CEST"} to replace the zz first

let str = `HH:mm z [on] D MMM YYYY
HH:mm zz [on] D MMM YYYY`

Object.entries({zz:"Central European Summer Time",z:"CEST"})
  .forEach(([key,val]) => str = str.replaceAll(key,val))
console.log(str)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading