我如何去除 javascript 中的 ipv6 地址?

How can i strip ipv6 address in javascript?

0000:0000:0000:0000:0000:0000:0000:0000
0000:0000:0000:0000:FFFF:0000:0002:AC11

如何有效地从上面的 ipv6 地址中删除 0000 部分以将其转换为:

0000
FFFF:0000:0002:AC11
//ip is a string
function stripIP(ip){
   var result = "";
   var arr = ip.match(/(?:0000:)*(.*)/);
   if(arr[1]){
    result = arr[1];
   }
 return result;
}

您可以使用:

 "0000:0000:0000:0000:FFFF:0000:0002:AC11".replace(/^(0000:)+/)

模式锚定在字符串的开头,并从那里删除重复出现的 0000:


演示https://regex101.com/r/jU7qM5/1

https://www.rfc-editor.org/rfc/rfc4291#section-2.2 and https://www.rfc-editor.org/rfc/rfc5952#section-4.2 所述,仅删除那些“0000:”会产生无效的 IPv6 表示。

“::”替换不应该只对一组 ceroes 进行,只能在地址中进行一次,并且必须在每个数字组内进行前导 0 剥离。还应考虑 IPv4 映射。

我会使用:(ip 是 IPv6 地址的 16 个字符的十六进制字符串表示形式)

function ip_notation(ip){
  var ip=ip.toLowerCase();
  //Watch out IPv6/IPv4 addresses notation
  //::ffff:XXX.XXX.XXX.XXX vs ::ffff:xxxx:xxxx
  if(ip.substr(0,24)=='00000000000000000000ffff' ){
    ip4= (ip.substr(24));
    ip4=ip4.match(/.{1,2}/g);
    for(k=0;k<4;k++){ip4[k]=parseInt(ip4[k],16);}
    ip='::ffff:'+ ip4.join('.');
    return ip;
  }
  field=ip.match(/.{1,4}/g);//Cut string in 4 digits fields
  //Find the longest ceroes fields group (maybe could be done with a regex)
  var max_ceroes_fields=0;
  var ceroes_fields=0;
  for(k=0;k<8;k++){
    if(field[k] == '0000') { //All '0' field
      ceroes_fields++;
      if( ceroes_fields > max_ceroes_fields ) { 
        max_ceroes_fields = ceroes_fields;
      }
    }else{//Not all '0' field
      ceroes_fields = 0;
    }
  }
  ip=field.join(":");//makes a string again, now with 4 digit groups
  //replace the longest ceroes group with "::"
  if(max_ceroes_fields>1) {
    var ceroes=(":0000".repeat(max_ceroes_fields)).substr(1);
    ip=ip.replace(ceroes,':');
    //Works fine if it is at the start or end, but produces ":::" in the middle
    ip=ip.replace(':::','::');
  }
  //Strip leading ceroes of fields
  ip.replace(/^(0){1,3}/,'');
  return ip;
}

试试 ip6 npm 包:https://www.npmjs.com/package/ip6

ip6 有助于规范化、缩写、划分子网、生成随机 subnets/hosts 和计算 IPv6 子网的大小范围。

let ip6 = require('ip6');
console.log(ip6.abbreviate('2001:0001:0000:0001:0000:0000:0000:0001'));
// 2001:1:0:1::1