Skip to content

Instantly share code, notes, and snippets.

@yaoelvon
Forked from bstees/abbreviate_ipv6.js
Created July 13, 2019 03:13
Show Gist options
  • Save yaoelvon/7049d7921bad27f6fb4c6a1a7571e29e to your computer and use it in GitHub Desktop.
Save yaoelvon/7049d7921bad27f6fb4c6a1a7571e29e to your computer and use it in GitHub Desktop.
Abbreviates full IPv6 addresses by removing the leading "0" and collapsing longest consecutive run of 16-bit zeros down to "::".
/* Abbreviate full ipv6 address
* By Brent Stees (http://facebook.com/brent.stees), 2014
* MIT Licenced, see http://www.opensource.org/licenses/mit-license.php */
function abbreviate_ipv6(ip){
if(ip.indexOf("::") == -1) {
// needs to be abbreviated
// remove leading zeros
ip = ip.replace(/^0+/,'').replace(/\:0/g,':');
// find longest run of consecutive zeros
var sixteens = ip.split(':'),
max = 0,
current = 0,
replace = "";
for(i=0; i<sixteens.length; i++) {
// test for non-numbers, this is so we can do an exact match later
if (!/\D/.test(sixteens[i])) {
sixteens[i] = parseInt(sixteens[i],10);
} else {
// do nothing
}
// check for "0" and increment
if (sixteens[i] === 0){
current++;
} else {
max = Math.max(current,max);
current = 0;
}
}
// build replace string
for (i=0; i<max; i++){
replace += ":0";
}
// replace
return sixteens.join(':').replace(replace,":");
} else {
// do nothing and return original value of ip
return ip;
}
}
// abbreviate_ipv6("FE02:0000:0000:0050:0000:0000:0000:0101");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment