[SalesForce] How to i match second-last char of a string with RegEx

Angular app!

I need to hide the 2 second-last char of a string and replace them with "XX".

what i got:

+391234567890

what i need

+39123456XX90

How can i match this with a RegEx?
I want to use this pattern in replace() method

Best Answer

That would look something like this:

let result = source.replace(/^(.*?).{2}(.{2})$/,'$1XX$2');

Where:

  • () is a "capture group"
  • ^ matches beginning of the string
  • .*? matches as few characters as necessary to fulfill pattern
  • .{2} matches two characters
  • $ matches the end of the string

And in the replacement string:

  • $# replaces the content of a capture group, numbered from 1 to #.