Home > Back-end >  Javascript replace a capture group to uppercase (not a duplicate)
Javascript replace a capture group to uppercase (not a duplicate)

Time:07-09

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" >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.

CodePudding user response:

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" >Lord</span>'
text = text.replaceAll(/<span style="font-variant.*?>(.*)<\/span>/g,
  (match, g1) => g1.toUpperCase());
console.log(text);

CodePudding user response:

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

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

text = text.replaceAll(/>(.*)<\/span>/g, function(_, group) {
  return `>${group.toUpperCase()}</span>`;
});
console.log(text);

  • Related