admin管理员组文章数量:1374952
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.
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.
Share Improve this question asked Sep 21, 2013 at 22:25 TransistorTransistor 3131 gold badge4 silver badges13 bronze badges 2- You just have to remove the leading zero. – elclanrs Commented Sep 21, 2013 at 22:25
- Ha, ha! But I want Javascript to do it, not me. Thanks for joining in. – Transistor Commented Sep 22, 2013 at 7:55
4 Answers
Reset to default 7function fix_ip(ip) { return ip.split(".").map(Number).join("."); }
JSFiddle (h/t @DavidThomas): http://jsfiddle/davidThomas/c4EMy/
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
Here is an option using string manipulation and conversion to integers. Looks ugly pared 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.
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);
本文标签: Remove ip address leading zeros with JavascriptStack Overflow
版权声明:本文标题:Remove ip address leading zeros with Javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743902564a2558938.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论