为什么';在JavaScript中,这个方法不能分配字符吗?
好的,下面是一个新手问题:为什么';在JavaScript中,这个方法不能分配字符吗?,javascript,string,dom,Javascript,String,Dom,好的,下面是一个新手问题: //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] = ti
//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?
我是否必须使用replace()函数在JS中执行类似的操作
多谢各位
[^\d]
是“非数字”的正则表达式
更详细地说,
[]
表示要匹配的“字符类”或字符组。\d
是0-9
或任何数字的快捷方式。字符类中的
^
对该类求反
function unformat(t)
{
return t.replace( /[^\d]/g, '' );
}
无论如何,在一个主要的浏览器中,你不能访问这样的字符串。您需要使用
str.charAt(x)
您肯定应该为此使用正则表达式
function unformatTime(time) {
return time.replace(/[^\d]/g, '');
}
在本例中,它查找任何非数字的内容并替换为空字符串。末尾的“g”表示“全球”,因此它将尽可能多次替换
括号内的这个表示“不”^
这表示“数字”\d
这意味着“全球”g
/[^\d]/,“
是做什么的吗?O_O我怀疑OP,考虑到他最初的做法让你哭了,可能也会很感激这一点+1@Stefan请注意,普通的“\D”(无括号)也表示“不是数字”。哦,为了能够传入任意次数并返回未格式化的时间数组,只需使用参数
数组而不是写入参数==>可能是一个愚蠢的问题,但是如果^
表示“不”,而\d
表示“非数字”…这是一个双重否定?@Pointy:我相信是“^”使\d被否定。(见其他人也有类似的问题)签出是的,可以,但是Javascript正则表达式语法已经有一个内置的“not a digit”特殊字符,它是“\D”(反斜杠后跟大写字母“D”)。@David Thomas no,“\D”表示“digit”,而“\D”表示“not a digit”-小写vs.大写。您可以单独使用“\D”,而不使用方括号(正如您可以使用不带方括号的“\D”来匹配数字)。@Pointy,ahhh我完全错过了大小写更改。。。我只买了这些眼镜=)(而且,这可能就是为什么我仍然觉得正则表达式很难理解的原因…)