Check if string contains only digits

Check if string contains only digits

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?

Solutions/Answers:

Solution 1:

how about

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

Solution 2:

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

Solution 3:

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

Solution 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);

Solution 5:

This is what you want

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

Solution 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

Related:  How to capture all scrolling events on a page without attaching an onscroll handler to every single container