1

I've the below Regex expression,

const regex = new RegExp('<(.*)>' + text + '<(.*)>');
renderer.setProperty(node, 'innerHTML', node.innerHTML.replace(regex, '<$1>' + replaceText + '<$2>'));

Instead of using '<$1>' and '<$2>', I need to use '<$open>' & '<$close>'

When I tried changing it's not working as expected.

How can it be done ?

user007
  • 189
  • 2
  • 13

1 Answers1

0

You seem to target ECMAScript 2018+ JS environment.

You may use (?<name>pattern) to define the named capturing groups in the pattern and $<name> named replacement backreferences in the replacement pattern to refer to the strings captured with the named groups.

You may also enhance the code a bit using

const regex = new RegExp('<(?<open>[^>]+)>' + text.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + '<(?<close>[^>]+)>');
renderer.setProperty(node, 'innerHTML', node.innerHTML.replace(regex, '<$<open>>' + replaceText.replace(/\$/g, '$$$$') + '<$<close>>'));

NOTES

  • (?<open>[^>]+) matches and captures the open tag into open named group and (?<close>[^>]+) captures the close tag into close named group with [^>]+ pattern: 1 or more chars other than >
  • text.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') is used to escape any special chars in text
  • replaceText.replace(/\$/g, '$$$$') is required to correctly handle $1 like literal strings in the replacement text.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563