Home > OS >  Replace two patterns at the same regex in JavaScript
Replace two patterns at the same regex in JavaScript

Time:12-15

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?

CodePudding user response:

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)

  • Related