preg_replace/preg_replace_callback PURE Javascript equivalent

I didn't know that but the string replace method support $X notation style and callback functions:

preg_replace
in pure javascript:


preg_replace_callback in pure javascript: