JavaScript - string regex backreferences

Like this:

str.replace(regex, function(match, $1, $2, offset, original) { return someFunc($2); })

Pass a function as the second argument to replace:

str = str.replace(/(\$)([a-z]+)/gi, myReplace);

function myReplace(str, group1, group2) {
    return "+" + group2 + "+";
}

This capability has been around since Javascript 1.3, according to mozilla.org.


Using ESNext, quite a dummy links replacer but just to show-case how it works :

let text = 'Visit http://lovecats.com/new-posts/ and https://lovedogs.com/best-dogs NOW !';

text = text.replace(/(https?:\/\/[^ ]+)/g, (match, link) => {
  // remove ending slash if there is one
  link = link.replace(/\/?$/, '');
  
  return `<a href="${link}" target="_blank">${link.substr(link.lastIndexOf('/') +1)}</a>`;
});

document.body.innerHTML = text;