sova sova - 9 months ago 35
Javascript Question

hiding last 2 segments of IP using JS/Regexp

I'm working on a Haiku Sharing site and I'd like to be able to star out some IP address segments to help anonymize submission data before it's shown to other users.

If I needed a regexp that satisfied the following: becomes 24.210.*.*

Is there a simple way to accomplish it?


Considering your comment:

It will always appear as an ip string because I am taking it directly from the request headers. Anticipating the format as #.#.#.# (standard ipv4) will do the trick.

You may remove 2 last .+digits sequences and then append .*.*:

var s = '';
console.log(s.replace(/(?:\.\d+){2}$/, '') + ".*.*");

Pattern explanation:

  • (?:\.\d+){2} - exactly 2 ({2}) sequences of:
    • \. - a literal dot symbol
    • \d+ - 1 or more digits
  • $ - end of string.