我想检查字符串是否只包含数字。我用了这个:

var isANumber = isNaN(theValue) === false;

if (isANumber){
    ..
}

但意识到它也允许+和-。基本上,我想确保输入只包含数字,没有其他字符。由于+100和-5都是数字,isNaN()不是正确的方法。 也许regexp就是我所需要的?任何建议吗?


当前回答

这就是你想要的

function isANumber(str){
  return !/\D/.test(str);
}

其他回答

如何

let isnum = /^\d+$/.test(val);

你可以使用下面的正则表达式:

^\d+$
c="123".match(/\D/) == null #true
c="a12".match(/\D/) == null #false

如果字符串只包含数字,它将返回null

string.match(/^[0-9]+$/) != null;

这里有一个不使用正则表达式的解决方案

const  isdigit=(value)=>{
    const val=Number(value)?true:false
    console.log(val);
    return val
}

isdigit("10")//true
isdigit("any String")//false