Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string contains a number in JavaScript?

I don't get how hard it is to discern a string containing a number from other strings in JavaScript.

Number('') evaluates to 0, while '' is definitely not a number for humans.

parseFloat enforces numbers, but allow them to be tailed by abitrary text.

isNaN evaluates to false for whitespace strings.

So what is the programatically function for checking if a string is a number according to a simple and sane definition what a number is?

like image 502
dronus Avatar asked Feb 28 '14 16:02

dronus


People also ask

How do you check if a string contains a number?

To find whether a given string contains a number, convert it to a character array and find whether each character in the array is a digit using the isDigit() method of the Character class.

How do you check if a variable contains a number in JavaScript?

In JavaScript, there are two ways to check if a variable is a number : isNaN() – Stands for “is Not a Number”, if variable is not a number, it return true, else return false. typeof – If variable is a number, it will returns a string named “number”.


2 Answers

By using below function we can test whether a javascript string contains a number or not. In above function inplace of t, we need to pass our javascript string as a parameter, then the function will return either true or false

function hasNumbers(t)
{
var regex = /\d/g;
return regex.test(t);
}    
like image 61
Ramu Vemula Avatar answered Sep 24 '22 19:09

Ramu Vemula


If you want something a little more complex regarding format, you could use regex, something like this:

var pattern = /^(0|[1-9][0-9]{0,2}(?:(,[0-9]{3})*|[0-9]*))(\.[0-9]+){0,1}$/;

Demo

enter image description here

I created this regex while answering a different question awhile back (see here). This will check that it is a number with atleast one character, cannot start with 0 unless it is 0 (or 0.[othernumbers]). Cannot have decimal unless there are digits after the decimal, may or may not have commas.. but if it does it makes sure they are 3 digits apart, etc. Could also add a -? at the beginning if you want to allow negative numbers... something like:

/^(-)?(0|[1-9][0-9]{0,2}(?:(,[0-9]{3})*|[0-9]*))(\.[0-9]+){0,1}$/;
like image 36
Dallas Avatar answered Sep 26 '22 19:09

Dallas