javascriptcompressionipv6regexp-replace

How to compress an IPV6 address in Javascript?


I have seen the code to compress IPV6 in java. The link specifies the same. Below is the code in Java . String resultString = subjectString.replaceAll("((?::0\\b){2,}):?(?!\\S*\\b\\1:0\\b)(\\S*)", "::$2"); But in Javascript I am confused as how can I get the regex expression to match the same . Can you share some pointers here?

Example :

fe80:00:00:00:8e3:a11a:2a49:1148

Result :

fe80::8e3:a11a:2a49:1148


Solution

  • You can do it by replacing

    \b(?:0+:){2,}
    

    with

    :
    

    function compIPV6(input) {
      return input.replace(/\b(?:0+:){2,}/, ':');
    }
    
    console.log('2001:db8:0:0:0:0:2:1', compIPV6('2001:db8:0:0:0:0:2:1'));
    console.log('fe80:00:00:00:8e3:a11a:2a49:1148', compIPV6('fe80:00:00:00:8e3:a11a:2a49:1148'));

    Check it out at regex101.