541

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 want to 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?

0

17 Answers 17

1077

how about

let isnum = /^\d+$/.test(val);
Sign up to request clarification or add additional context in comments.

12 Comments

@dewwwald: Some languages implement it differently, but in JavaScript, \d is exactly equivalent to [0-9].
Here you can find documentation about how Regular Expressions work
/^\d*$/ instead, if you find an empty string containing only digits.
@DrorBar I’m sorry for my poor English and let me rephrase it: “if you consider an empty string to be having only digits.”
This solution is good, but it's true for things like 000000001
|
102
string.match(/^[0-9]+$/) != null;

Comments

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

3 Comments

It's considered bad practice in Javascript to modify prototypes of built-in objects (principle of least surprise, and potential conflicts in future ECMA versions) - consider isNumber = () => /^\d+$/.test(this); instead, and use as console.log(isNumber("123123));
FWIW, in 2009 when this answer was posted, it was not yet considered a bad practice. Several jQuery competitors that existed then, before jQuery had yet to win out, all practiced prototype extensions.
still, it was a bad practice, even though it wasn't considered as such by jQuery lovers.
22

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 Comments

however if you don't use a float rather int it will return false maybe using "?" after ".\" solved that. I suggest this /^\d+[\.,\,]?\d+$/.test(value) to allow both comma and point decimal (later maybe can transform comma to point)
@Lucke, the regex you suggested will only be able to find numbers with a decimal or higher than 9. If you change the first \d+ to \d*?, it will be able to match 0 - 9, as well as numbers such as .333
Close: var isNumber = /^\d*\.?\d+$/.test(value) -- matches '3.5', '.5', '3' -- does not match '3.'
Since 2009, this question was always asking how to validate that a string contains only numbers. This post is the correct answer to a different question.
@PeterHollingsworth This doesn't match negative numbers like -100.2
20

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

3 Comments

This will also return true for empty string '', and an empty array [], an array of integers [1, 2, 3] (once they are < 10). It's more prone to bugs/misuse than the basic regular expression /^\d+$/ I think
This is far easier to read than a Regex, and is easily expandable to other approaches. When used in TypeScript, and in conjunction with length checks, this can be very elegant.
I like its uniqueness, but also, this solution is most “resource consuming“ to use and not scalable in performance intensive or data heavy client-side, due to requiring 10x operations for every character of input.
12

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.

Comments

11

This is what you want

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

3 Comments

This answer allows an empty string to pass as a valid number.
@mickmackusa technically, that is exactly what the asker requested: "a string that contains only digits"
An empty string does not contain only digits; it's empty -- it contains only nothing. Also isANumber() is a misleading function name -- a valid number may contain a positive/negative sign or a dot as a decimal point separating character.
8

in case you need integer and float at same validation

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

1 Comment

Since 2009, this question was always asking how to validate that a string contains only numbers. This post is the correct answer to a different question.
6
function isNumeric(x) {
    return parseFloat(x).toString() === x.toString();
}

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

Comments

4

Well, you can use the following regex:

^\d+$

2 Comments

Does not work for floating point numbers.
Well, floating point numbers don't only contain digits. They may very well also include a decimal point. And since the question was about digits instead of things that can be parsed as a number, the answer stands.
1

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 

1 Comment

Since 2009, this question was always asking how to validate that a string contains only numbers. This post is the correct answer to a different question.
1

If you want to leave room for . you can try the below regex.

/[^0-9.]/g

Comments

0

If you use jQuery:

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

Comments

0

This works:

let output=Number.isInteger( Number(input) );

if(output) console.log('Input string contains only numbers');
else console.log('Input string contains does not contain only numbers');

Comments

0

This checks non-Latin (aka non-English) digits too:

/^\p{digit}+$/u.test("1234۱۲۳۴"); // true
// OR
/^\p{Nd}+$/u.test("1234۱۲۳۴");    // true

Comments

-1

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

3 Comments

for 0 it would be false
For 0x123 would be true :/
any number with a space at the end will evaluate to true
-2
c="123".match(/\D/) == null #true
c="a12".match(/\D/) == null #false

If a string contains only digits it will return null

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.