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
Add a ment  | 

4 Answers 4

Reset to default 7
function 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