Capture groups~ Browser APIs ~

Capture groups

Like most programming languages JavaScript supports regular expressions. I'm writing software for more than 15 years, and I've never been good with this, but I want to share my favorite feature - capture groups. It can solve a whole set of problems with just one line of code.

I recently renamed a file from script.js to script.prod.js. Capture groups are perfect for this:

function renameFile(file, postfix) {
  return file.replace(
    /(\.(js|ts|jsx|tsx))/i,
    `.${postfix}$1`
  );
}

console.log(renameFile("public/js/script.js", "prod"));
// public/js/script.prod.js

The (\.(js|ts|jsx|tsx)) defines a capture group that matches .js. Later in the second argument of the replace method, we have it as $1. $2 will contain the value of the second capture group and so on.