0

I am trying to write javascript code that would trim the last section of an ip address (string), such as 123.456.789.012, and return the trimmed ip string, which in the case of the example would be 123.456.789

How would this be done (regex?)?

Please excuse my lack of proper terminology. I hope this makes enough sense.

Thanks

user31415
  • 446
  • 7
  • 16

3 Answers3

1

You could find the 3rd occurrence of a period in your IP string and then take the substring up to that index. Finding the nth occurrence of a character in a string in javascript

Community
  • 1
  • 1
kcborys
  • 316
  • 1
  • 11
1

Array#slice could be used over String#split and then Array#join

var splitted = '123.456.789.012'.split('.');
var op = splitted.slice(0, splitted.length - 1).join('.');
console.log(op);
Rayon
  • 36,219
  • 4
  • 49
  • 76
0

Try this:-

    var a = "123.456.789.012"; 
    var result = a.substr(0,((a.length - a.indexOf(".")) - 1));
    console.log(result);
Vivek Pratap Singh
  • 9,326
  • 5
  • 21
  • 34