NodeJS Replace Matched String From Regex

How to match regex from string and replace matched string $1-$9

$1 = matched index 1 and so on

for example: were going to replace all markdown extensions to html extension.

const str = `[text1](url.md) [txt](http://webmanajemen.com/post.md)`; // string to replace
const regex = /\[.*\]\(.*(.md)\)/gm; // regex to match group index 1 (.md)
if (regex.exec(str)) { // check if regex match
  const replaced = str.replace(regex, function (wholeMatch, index1) {
    console.log(wholeMatch, index1);
    return wholeMatch.replace(index1, ".html"); // replace .md to .html
  });
  console.log(replaced); // [text1](url.html) [txt](http://webmanajemen.com/post.html)
}