0

On my website, a user has an activity log that he can access to see his recent actions. Within these actions, the IP is shown only for the user, for example:

2020-04-04-09:59:02 Action X 192.168.1.251  You did Action X bla bla bla

Of course, the IP is usually the client's external IP.

What I am trying to do, is mask/hide the ip when the user copies his activity log so he doesn't show it to others by mistake.

What I tried is the next:

document.addEventListener('copy', function(t) {
  var e = window
    .getSelection()
    .toString()
    .replace(
      /((0|1[0-9]{0,2}|2[0-9]?|2[0-4][0-9]|25[0-2.0-98*-5]|[3-9][0-9]?)\.){3}(0|1[0-9]{0,2}|2[0-9]?|2[0-4][0-9]|25[0-5]|[3-9][0-9]?)/g,
      '',
    );
  t.clipboardData.setData('text/plain', e), t.preventDefault();
});

When I try to copy the text and paste it here, I get:

2020-04-04-09:59:02 Action X 1 You did Action X bla bla bla

The code almost work, but I keep getting this 1. I couldn't find a way to fix it yet.

JSFiddle: https://jsfiddle.net/aoq1k9nu/

Any help is appreciated.

felixmosh
  • 32,615
  • 9
  • 69
  • 88
Paul Karam
  • 4,052
  • 8
  • 30
  • 53

1 Answers1

3

You can simplify the regex if you aren't worried about other things that approximate an ipv4 address: /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/

Or if you want to be more careful from https://www.regular-expressions.info/ip.html:

/\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/
Zachary Haber
  • 10,376
  • 1
  • 17
  • 31