Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 702
patad Avatar asked Nov 22 '09 15:11

patad


People also ask

How do you check if input contains only numbers?

To check for all numbers in a field To get a string contains only numbers (0-9) we use a regular expression (/^[0-9]+$/) which allows only numbers. Next, the match() method of the string object is used to match the said regular expression against the input value.

How do you check if a string contains only digits in C?

You can use the isdigit() macro to check if a character is a number. Using this, you can easily write a function that checks a string for containing numbers only.

How do you check if a string is all digits in Java?

To check if String contains only digits in Java, call matches() method on the string object and pass the regular expression "[0-9]+" that matches only if the characters in the given string are digits.

How do I check if a string contains only numbers in SQL?

The ISNUMERIC() function tests whether an expression is numeric. This function returns 1 if the expression is numeric, otherwise it returns 0.


2 Answers

how about

let isnum = /^\d+$/.test(val); 
like image 139
Scott Evernden Avatar answered Sep 20 '22 15:09

Scott Evernden


string.match(/^[0-9]+$/) != null; 
like image 32
Jason S Avatar answered Sep 19 '22 15:09

Jason S