簡體   English   中英

檢查輸入字符串中是否存在至少一個非數字值

[英]Check for occurrence of at least one non numeric value in input string

我已經嘗試了許多正則表達式,但仍然無法正常工作。 請說出我可能錯了的地方:

  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()因為我已經刪除了它,並且也嘗試過。

使用\\D匹配非數字字符

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

演示:

 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)" /> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM