0

I am aware of Replace a Regex capture group with uppercase in Javascript

That is for replacing the entire match and not a () match.

Here is my problem:

var text = '<span style="font-variant: small-caps" class="small-caps">Lord</span>'
text = text.replaceAll(/<span style="font-variant.*?>(.*)<\/span>/g, function (v) { return v.toUpperCase(); });
console.log(text);

This returns the entire tag as uppercase and not the actual text in (.*).

I just want to replace the span tag with just the uppercase of the innertext. There is more than one span tag as well in the actual text variable.

Barmar
  • 741,623
  • 53
  • 500
  • 612
John Smith
  • 3,493
  • 3
  • 25
  • 52

2 Answers2

4

Capture groups are passed as additional arguments to the callback function. So use the argument with the capture.

var text = '<span style="font-variant: small-caps" class="small-caps">Lord</span>'
text = text.replaceAll(/<span style="font-variant.*?>(.*)<\/span>/g,
  (match, g1) => g1.toUpperCase());
console.log(text);
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

You can also use />(.*)<\/span>/g

var text =
  '<span style="font-variant: small-caps" class="small-caps">Lord</span>';

text = text.replaceAll(/>(.*)<\/span>/g, function(_, group) {
  return `>${group.toUpperCase()}</span>`;
});
console.log(text);
DecPK
  • 24,537
  • 6
  • 26
  • 42