Skip to content
Advertisement

Javascript replace a capture group to uppercase (not a duplicate)

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.

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement