检查字符串是否只包含数字

时间:2022-07-30 01:42:33

I want to check if a string contains only digits. I used this:

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

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

if (isANumber){
    ..
}

.. but realized that it also allows + and -. Basically I wanna make sure the input contains ONLY digits and no other letters. Since +100 and -5 are both numbers, isNaN, is not the right way to go. Perhaps a regexp is what I need? Any tips?

. .但是意识到它也允许+和-。基本上,我想确保输入只包含数字而不包含其他字母。因为+100和-5都是数字,isNaN不是正确的方法。也许我需要一个regexp ?任何建议吗?

6 个解决方案

#1


381  

how about

如何

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

#2


43  

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

#3


10  

String.prototype.isNumber = function(){return /^\d+$/.test(this);}
console.log("123123".isNumber()); // outputs true
console.log("+12".isNumber()); // outputs false

#4


4  

This is what you want

这就是你想要的

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

#5


4  

If you want to even support for float values (Dot separated values) then you can use this expression :

如果你甚至想支持浮点值(点分隔值),那么你可以使用这个表达式:

var isNumber = /^\d+\.\d+$/.test(value);

#6


2  

Well, you can use the following regex:

你可以使用下面的regex:

^\d+$

#1


381  

how about

如何

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

#2


43  

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

#3


10  

String.prototype.isNumber = function(){return /^\d+$/.test(this);}
console.log("123123".isNumber()); // outputs true
console.log("+12".isNumber()); // outputs false

#4


4  

This is what you want

这就是你想要的

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

#5


4  

If you want to even support for float values (Dot separated values) then you can use this expression :

如果你甚至想支持浮点值(点分隔值),那么你可以使用这个表达式:

var isNumber = /^\d+\.\d+$/.test(value);

#6


2  

Well, you can use the following regex:

你可以使用下面的regex:

^\d+$