2013-05-01 87 views
1

如何獲取此代碼只返回一個虛假警報,因爲它包含一個數字,因爲它包含一個數字,當我檢查字符串「name」中的內容應該全部小寫阿爾法?確認只有數字包含在Javascript中的字符串中

var name = "Bob1"; 
var i = 0; 
var name = name.toLowerCase() 

for(i=0; i<name.length; i++){ 
    if((name.charCodeAt(i)>96) && (name.charCodeAt(i)<123)) { 
    alert("true"); 
    } else {alert("false");} 
} 
+2

。 @Aquillo建議使用正則表達式是一個更乾淨的版本,但如果你想for循環中斷;是命令您尋找 – brendosthoughts 2013-05-01 05:53:07

回答

5

我會用正則表達式去爲這一個:

if(name.match(/\d/)) { 
    // this contains at least one number 
} 
else { 
    // this doesn't contain any numbers 
} 

因爲人們會注意到upvoted答案,我將引用你的情況下,更好的解決方案。這是由Ray Toal提供的(信用/他贊成這種情況):

既然你只是想讓你的name的alpha爲0,那麼你也可以直接處理這個(這也包括連字符等問題) :

if(name.match(/^[a-z]+$/)) { 
    // this contains only undercase alpha's 
} 
else { 
    // this contains at least one character that's not allowed 
} 
0

添加break語句,這樣新的代碼看起來像這樣的if語句

if((name.charCodeAt(i)>96) && (name.charCodeAt(i)<123)) 
{alert("true"); 
    break; 
}else 

內...基本上它只是退出for循環(同一命令工作的同時,環路以及)

+0

... @Aquillo建議使用正則表達式是一個非常乾淨的版本,但如果你想for循環'break;'是命令你尋找 – brendosthoughts 2013-05-01 05:52:34

0

休息一下;在else裏面,所以它得到了循環警報虛假首次

1

後,如果您想提醒所有的人物都在範圍a通過z你可以使用正則表達式,指出直接

alert(/^[a-z]+$/.test(name1.toLowerCase())) 

您也可以反轉的條件,說你想要的值false如果字符串包含至少一個非字母:

alert(!(/[^a-z]/.test(name1.toLowerCase()))) 
相關問題