问题
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 an input
contains ONLY digits and no other characters. Since +100
and -5
are both numbers, isNaN()
is not the right way to go.
Perhaps a regexp is what I need? Any tips?
回答1:
how about
var isnum = /^\d+$/.test(val);
回答2:
string.match(/^[0-9]+$/) != null;
回答3:
String.prototype.isNumber = function(){return /^\d+$/.test(this);}
console.log("123123".isNumber()); // outputs true
console.log("+12".isNumber()); // outputs false
回答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);
回答5:
This is what you want
function isANumber(str){
return !/\D/.test(str);
}
回答6:
Here's another interesting, readable way to check if a string contains only digits.
This method works by splitting the string into an array using the spread operator, and then uses the every() method to test whether all elements (characters) in the array are included in the string of digits '0123456789'
:
const digits_only = string => [...string].every(c => '0123456789'.includes(c));
console.log(digits_only('123')); // true
console.log(digits_only('+123')); // false
console.log(digits_only('-123')); // false
console.log(digits_only('123.')); // false
console.log(digits_only('.123')); // false
console.log(digits_only('123.0')); // false
console.log(digits_only('0.123')); // false
console.log(digits_only('Hello, world!')); // false
回答7:
Well, you can use the following regex:
^\d+$
回答8:
Here is a solution without using regular expressions:
function onlyDigits(s) {
for (let i = s.length - 1; i >= 0; i--) {
const d = s.charCodeAt(i);
if (d < 48 || d > 57) return false
}
return true
}
where 48 and 57 are the char codes for "0" and "9", respectively.
回答9:
function isNumeric(x) {
return parseFloat(x).toString() === x.toString();
}
Though this will return false
on strings with leading or trailing zeroes.
回答10:
c="123".match(/\D/) == null #true
c="a12".match(/\D/) == null #false
If a string contains only digits it will return null
来源:https://stackoverflow.com/questions/1779013/check-if-string-contains-only-digits