2011-10-27 18 views
0

想知道錯誤如何纔會出現在IE中 可以通過修改工作嗎? 3q。字符串處理函數不能僅在IE中正常工作

Function 
input: 192.2.09.001 
output: 192.2.9.1 

[email protected] 
input: 192.2.09.001 
output: undefinedundefinedundefined.undefined.undefinedundefined.undefinedundefinedundefined 

Code: ip_normalize(ip)

function remove_0(input) 
{ 

    var i; 
    var output_string=""; 
    var tag=0; 
    for (i=0; i< input.length ; i++) 
    { 
      if(i==input.length-1 || tag==1) 
      { 
        output_string+= input[i]; 
      } 
      else 
      { 
        if(input[i]!='0') 
        { 
          output_string+= input[i]; 
          tag=1; 
        } 
      } 
    } 
    return output_string; 
} 

function ip_normalize(ip) 
{ 
    var ip_s = ip.split('.'); 
    var ip_n = ""; 
    var ip1="",ip2="",ip3="",ip4=""; 
    if(ip_s.length!=4) 
      return ip; 
    ip1 = remove_0(ip_s[0]); 
    ip2 = remove_0(ip_s[1]); 
    ip3 = remove_0(ip_s[2]); 
    ip4 = remove_0(ip_s[3]); 

    ip_n = ip1 + '.' + ip2 + '.' + ip3 + '.' + ip4; 

    return ip_n; 
} 

回答

2

不能只需使用:

function ip_normalize(ip) 
{ 
    var ip_s = ip.split('.', 4); 
    if (ip_s.length != 4) return ip; 
    return parseInt(ip_s[0], 10) + "." + 
      parseInt(ip_s[1], 10) + "." + 
      parseInt(ip_s[2], 10) + "." + 
      parseInt(ip_s[3], 10); 
} 
+0

3q,很好的建議,我會嘗試它可以在IE上工作 – LIC

+0

這是錯誤的,因爲'parseInt(「010」)=== 8'! –

+0

@AndrewD .:對,我剛剛編輯過我的帖子。謝謝:) – Marco

0

你可以嘗試以下方法:

function cleanIP(IP) { 
     var result = [], 
      array = ip.split('.'); 
     for (i in array) { 
      result.push(+array[i]); 
     } 
     return result.join('.'); 
    } 

來看,它通過調用

cleanIP("192.168.001.010"); 

寫了一個新函數,然後把IE搞亂了,

+0

酷處理 – LIC

1
function normalizeIPv4(str) { 
    var ipA=str.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/); 
    if(!ipA)return; // undefined because string not in valid format 
    for(var i=1;i<5;i++) { 
    ipA[i]=(+ipA[i]); 
    if(!(ipA[i]>=0&&ipA[i]<=255))return; // undefined because string not in valid format 
    } 
    return ipA[1]+"."+ipA[2]+"."+ipA[3]+"."+ipA[4]; 
} 
+0

一個偉大的功能名稱,我喜歡這一個,因爲它也驗證IP。 – Stefan