如何使用Javascript将我的010.017.007.152样式地址(便于数据库排序)转换为10.17.7.152以显示和超链接?
样品: 010.064.214.210 010.064.000.150 010.064.017.001 127.000.0.001 10.0.00.000
非常感谢。
答案 0 :(得分:7)
function fix_ip(ip) { return ip.split(".").map(Number).join("."); }
JSFiddle(h / t @DavidThomas):http://jsfiddle.net/davidThomas/c4EMy/
答案 1 :(得分:2)
使用正则表达式,您可以替换许多模式。像这样的东西可以起作用......
var ip = "010.064.214.210"
var formatted = ip.replace(/(^|\.)0+(\d)/g, '$1$2')
console.log(formatted)
正则英语正则表达式
/ # 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
答案 2 :(得分:2)
这是一个使用字符串操作和转换为整数的选项。与regex solution by Billy Moon相比看起来很丑陋,但有效:
var ip = "010.064.000.150".split('.').map(function(octet){
return parseInt(octet, 10);
}).join('.');
或者,一点点清洁:
var ip = "010.064.000.150".split('.').map(function(octet){
return +octet;
}).join('.');
Nirk's solution使用类似的方法,甚至更短,请查看。
答案 3 :(得分:1)
您可以使用此代码:
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);