Reputation: 313
How do I convert my 010.017.007.152 style addresses (for easy database sorting) to 10.17.7.152 for display and hyperlinks using Javascript?
Samples: 010.064.214.210 010.064.000.150 010.064.017.001 127.000.0.001 10.0.00.000
Many thanks.
Upvotes: 2
Views: 2302
Reputation: 3397
You can use this code :
var ip = " 010.017.007.152";
var numbers = ip.split(".");
var finalIp = parseInt(numbers[0]);
for(var i = 1; i < numbers.length; i++){
finalIp += "."+parseInt(numbers[i]);
}
console.log(finalIp);
Upvotes: 1
Reputation: 71939
Here is an option using string manipulation and conversion to integers. Looks ugly compared to the regex solution by Billy Moon, but works:
var ip = "010.064.000.150".split('.').map(function(octet){
return parseInt(octet, 10);
}).join('.');
Or, a tiny bit cleaner:
var ip = "010.064.000.150".split('.').map(function(octet){
return +octet;
}).join('.');
Nirk's solution uses a similar method, and is even shorter, check it out.
Upvotes: 2
Reputation: 58619
With regex, you can make replacements to many patterns. Something like this could work...
var ip = "010.064.214.210"
var formatted = ip.replace(/(^|\.)0+(\d)/g, '$1$2')
console.log(formatted)
Regex in plain english...
/ # start regex
(^|\.) # start of string, or a full stop, captured in first group referred to in replacement as $1
0+ # one or more 0s
(\d) # any digit, captured in second group, referred to in replacement as $2
/g # end regex, and flag as global replacement
Upvotes: 3
Reputation: 22925
function fix_ip(ip) { return ip.split(".").map(Number).join("."); }
JSFiddle (h/t @DavidThomas): http://jsfiddle.net/davidThomas/c4EMy/
Upvotes: 7