Last active
July 13, 2019 03:13
-
-
Save bstees/070540786e4975038d52 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 "::".
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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