检查输入字符串中是否至少出现一个非数字值

问题描述:

我尝试了很多正则表达式,但它仍然无法正常工作。请告诉我可能出错的地方:检查输入字符串中是否至少出现一个非数字值

  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

使用\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)" />