代码之家  ›  专栏  ›  技术社区  ›  T.T.T.

为什么这个方法不能在javascript中分配字符?

  •  3
  • T.T.T.  · 技术社区  · 15 年前

    好的,下面是一个新手问题:

    //function removes characters and spaces that are not numeric.
    
    // time = "2010/09/20 16:37:32.37"
    function unformatTime(time) 
    {       
    
        var temp = "xxxxxxxxxxxxxxxx";
    
        temp[0] = time[0];
        temp[1] = time[1];
        temp[2] = time[2];
        temp[3] = time[3];
        temp[4] = time[5];
        temp[5] = time[6];
        temp[6] = time[8];
        temp[7] = time[9];
        temp[8] = time[11];
        temp[9] = time[12];
        temp[10] = time[14];
        temp[11] = time[15];
        temp[12] = time[17];
        temp[13] = time[18];
        temp[14] = time[20];
        temp[15] = time[21];   
    
    
    }
    

    在Firebug中,我可以看到有时的字符没有分配给temp? 在JS中,是否必须使用replace()函数来执行类似的操作?

    谢谢您。

    2 回复  |  直到 15 年前
        1
  •  4
  •   Stefan Kendall    15 年前

    [^\d] 是“非数字”的正则表达式。

    更详细地说,

    [] 表示要匹配的“字符类”或字符组。
    \d 是的快捷方式 0-9 ,或者任何数字。
    ^ 在character类中,否定类。

    function unformat(t)
    {
       return t.replace( /[^\d]/g, '' );
    }
    

    无论如何,您不能在一个主要浏览器中访问这样的字符串。你需要使用 str.charAt(x) .

        2
  •  3
  •   Stephen    15 年前

    您应该为此使用正则表达式。

    function unformatTime(time) {
        return time.replace(/[^\d]/g, '');
    }
    

    在本例中,它查找任何非数字的内容,并用空字符串替换。末尾的“G”表示“全局”,因此它将尽可能多次替换。

    • ^ 括号内的意思是“不”
    • \d 这意味着“数字”
    • g 这意味着“全球”