[javascript] 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?

This question is related to javascript numbers digits

The answer is


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

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.


Here's a Solution without using regex

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

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

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':

_x000D_
_x000D_
const digits_only = string => [...string].every(c => '0123456789'.includes(c));_x000D_
_x000D_
console.log(digits_only('123')); // true_x000D_
console.log(digits_only('+123')); // false_x000D_
console.log(digits_only('-123')); // false_x000D_
console.log(digits_only('123.')); // false_x000D_
console.log(digits_only('.123')); // false_x000D_
console.log(digits_only('123.0')); // false_x000D_
console.log(digits_only('0.123')); // false_x000D_
console.log(digits_only('Hello, world!')); // false
_x000D_
_x000D_
_x000D_


This is what you want

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

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

If a string contains only digits it will return null


it checks valid number integers or float or double not a string

regex that i used

simple regex

 1. ^[0-9]*[.]?[0-9]*$

advance regex

 2. ^-?[\d.]+(?:e-?\d+)?$    

eg:only numbers

_x000D_
_x000D_
var str='1232323';
var reg=/^[0-9]*[.]?[0-9]*$/;

console.log(reg.test(str))
_x000D_
_x000D_
_x000D_

it allows

eg:123434

eg:.1232323

eg:12.3434434

it does not allow

eg:1122212.efsffasf

eg:2323fdf34434

eg:0.3232rf3333

advance regex

////////////////////////////////////////////////////////////////////

int or float or exponent all types of number in string

^-?[\d.]+(?:e-?\d+)?$

eg:13123123

eg:12344.3232

eg:2323323e4

eg:0.232332


function isNumeric(x) {
    return parseFloat(x).toString() === x.toString();
}

Though this will return false on strings with leading or trailing zeroes.


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

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

_x000D_
_x000D_
var str='1232323a.1';
var reg=/^[0-9]*[.]?[0-9]*$/;

console.log(reg.test(str))
_x000D_
_x000D_
_x000D_


in case you need integer and float at same validation

/^\d+\.\d+$|^\d+$/.test(val)


Well, you can use the following regex:

^\d+$

if you want to include float values also you can use the following code

theValue=$('#balanceinput').val();
var isnum1 = /^\d*\.?\d+$/.test(theValue);
var isnum2 =  /^\d*\.?\d+$/.test(theValue.split("").reverse().join(""));
alert(isnum1+' '+isnum2);

this will test for only digits and digits separated with '.' the first test will cover values such as 0.1 and 0 but also .1 , it will not allow 0. so the solution that I propose is to reverse theValue so .1 will be 1. then the same regular expression will not allow it .

example :

 theValue=3.4; //isnum1=true , isnum2=true 
theValue=.4; //isnum1=true , isnum2=false 
theValue=3.; //isnum1=flase , isnum2=true 

If you use jQuery:

$.isNumeric('1234'); // true
$.isNumeric('1ab4'); // false

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to numbers

how to display a javascript var in html body How to label scatterplot points by name? Allow 2 decimal places in <input type="number"> Why does the html input with type "number" allow the letter 'e' to be entered in the field? Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array Input type "number" won't resize C++ - how to find the length of an integer How to Generate a random number of fixed length using JavaScript? How do you check in python whether a string contains only numbers? Turn a single number into single digits Python

Examples related to digits

C++ - how to find the length of an integer Gets last digit of a number Sum the digits of a number Get number of digits with JavaScript How do I separate an integer into separate digits in an array in JavaScript? C: how to break apart a multi digit number into separate variables? Show a leading zero if a number is less than 10 How to tell if string starts with a number with Python? in python how do I convert a single digit number into a double digits string? Controlling number of decimal digits in print output in R