【问题标题】:How to get all but last section of known ip address如何获取已知IP地址的最后一部分
【发布时间】:2016-11-07 16:23:26
【问题描述】:

我正在尝试编写 javascript 代码来修剪 IP 地址(字符串)的最后一部分,例如 123.456.789.012,并返回修剪后的 ip 字符串,在示例中为 123.456.789

这将如何完成(正则表达式?)?

请原谅我缺乏正确的术语。我希望这有足够的意义。

谢谢

【问题讨论】:

  • 123.456.789.012 不是有效的 IP 地址 ;-)

标签: javascript ip


【解决方案1】:

Array#slice 可以用在String#split 上,然后是Array#join

var splitted = '123.456.789.012'.split('.');
var op = splitted.slice(0, splitted.length - 1).join('.');
console.log(op);

【讨论】:

    【解决方案2】:

    您可以在 IP 字符串中找到第三次出现的句点,然后将子字符串带到该索引。 Finding the nth occurrence of a character in a string in javascript

    【讨论】:

      【解决方案3】:

      试试这个:-

          var a = "123.456.789.012"; 
          var result = a.substr(0,((a.length - a.indexOf(".")) - 1));
          console.log(result);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-29
        • 1970-01-01
        • 1970-01-01
        • 2014-05-26
        • 1970-01-01
        • 2010-12-26
        • 2012-12-05
        相关资源
        最近更新 更多