2015-10-05 91 views
1

我嘗試了很多正則表達式,但它仍然無法正常工作。請告訴我可能出錯的地方:檢查輸入字符串中是否至少出現一個非數字值

  1. 我從用戶那裏獲得輸入(期待它只是數字)。
  2. myArray = str.replace(/\s+/g,"").split(""); //remove any spaces if present & split each character
  3. if(/^[0-9]/.test(myArray)) console.log("Make sure you enter all number"); else console.log("Successful");

輸出,如果給出如下輸入(STR):

  • 455e5 7523 1455 - > 「請確認您輸入所有數字」

  • 4555 2375 2358 - >「確保您輸入了所有號碼」而不是「成功」

我已經試過/^[0-9]+//^\d+$//(^\d)*/和許多類似的表達。它沒有幫助我。 是因爲split(),因爲我已經刪除它,也嘗試過。

+0

代碼工作而不 '分裂()' 功能很好。我已經將它們分割成字符串/字符串數組這是問題:) – rkkkk

回答

0

使用\D匹配非數字字符

if(/\D/.test(myArray)) 
    console.log("Make sure you enter all number"); 
else 
    console.log("Successful"); 

DEMO:

function test(myArray) { 
 
    if (/\D/.test(myArray.replace(/\s+/g,""))) 
 
    console.log("Make sure you enter all number"); 
 
    else 
 
    console.log("Successful"); 
 
}
<input oninput="test(this.value)" />

或者你可以使用[^\d\s]除外數字和空間

匹配字符

function test(myArray) { 
 
    if (/[^\d\s]/.test(myArray)) 
 
    console.log("Make sure you enter all number"); 
 
    else 
 
    console.log("Successful"); 
 
}
<input oninput="test(this.value)" />

相關問題