用普通的for+if语句判断字符串中字母,数字,空格,其他字符的数目
function func(string){
var str=string,word=0,num=0,space=0,other=0;
for(var i=0,count=str.length;i<count;i++)
{if('A'<=str.charAt(i)&&str.charAt(i)<='Z'||'a'<=str.charAt(i)&&str.charAt(i)<='z')
word++;
else if(0<=str.charAt(i)&&str.charAt(i)<=9)
num++;
else if(str.charAt(i)==' ')
space++;
else
other++;
}
document.write('word:'+word+"<br/>");//2
document.write('number:'+num+"<br/>");//3?为什么这样?
document.write('space:'+space+"<br/>");//0?为什么?
document.write('otner char:'+other+"<br/>");//3
}
func('12qw *&^');
else if(0<=str.charAt(i)&&str.charAt(i)<=9)
改成
else if('0'<=str.charAt(i)&&str.charAt(i)<='9')
一个是数字0~9,一个是数字字符'0'~'9',两者是不一样的