我怎样才能在javascript中删除ipv6地址?

时间:2016-04-13 05:34:50

标签: javascript ipv6

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

如何有效地剥离上述ipv6地址中的0000部分以将其转换为:

0000
FFFF:0000:0002:AC11

4 个答案:

答案 0 :(得分:3)

您可以使用:

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

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

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

答案 1 :(得分:2)

$scope.data = [{sweet:something},{sweet:somethingelse}];
$scope.sweet='';
$scope.sweetIndx='';
$scope.getItem = function($index,item) {
  $scope.sweetIndx = $index;//so you get the index into the array
  $scope.sweet = item;//you also get the name of the item
  console.log($scope.sweet);
}

答案 2 :(得分:0)

正如http://tools.ietf.org/html/rfc4291#section-2.2http://tools.ietf.org/html/rfc5952#section-4.2解释那些“0000:”可以产生无效的IPv6表示。

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

我使用:(ip是16个字符的HEX字符串表示IPv6地址)

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;
}

答案 3 :(得分:0)

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

ip6有助于规范化,缩写,划分子网,生成随机子网/主机并计算IPv6子网的大小范围。

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