简体   繁体   中英

Remove ip address leading zeros with Javascript?

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.

function fix_ip(ip) { return ip.split(".").map(Number).join("."); }

JSFiddle(h / t @DavidThomas): http//jsfiddle.net/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 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM