user31415
user31415

Reputation: 466

How to get all but last section of known ip address

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

Upvotes: 0

Views: 122

Answers (3)

Vivek Pratap Singh
Vivek Pratap Singh

Reputation: 9974

Try this:-

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

Upvotes: 0

Rayon
Rayon

Reputation: 36599

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

Upvotes: 1

kcborys
kcborys

Reputation: 316

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

Upvotes: 1

Related Questions