Ad
  • Default User Avatar

    Some useful links: .replace(), ternary operator, comma operator, arrow functions.

    1. Arrow function match => (matches++, matches % n ? match : newValue) is executed for every new RegExp(oldValue, "g") match.
    2. Here we have a comma operator ( (matches++), (matches % n ? match : newValue) ), so operands are evaluated from the left to the right and the last operand is returned.
    • matches++ increments our occurrences counter; now we have the current occurrence number.
    • (matches % n) ? match : newValue expression uses ternary operator. If occurrence number fits with nth rule - change it to newValue, otherwise left match untouched by returning itself.

    Note: using comma operator in a production code considered as a bad practice unless other is defined by team/company rules.

    The way of avoiding comma operator in here is replacing matches++, matches % n ? match : newValue with ++matches % n ? match : newValue, which is also a kind of bad practice. Incrementing value should take own separate line of code.

  • Custom User Avatar

    could you explain me your code with a little more details?