0

How could I do it in Node.js to recognize if a string is a valid number?

Here are some examples of what I want:

"22"     => true
"- 22"   => true
"-22.23" => true
"22a"    => false
"2a2"    => false
"a22"    => false
"22 asd" => false

I dont actually need to return "true" or "false", but I need an unequivocally way to distinguish them. It seems like isNaN isnt available in node.js...

Enrique Moreno Tent
  • 22,811
  • 31
  • 96
  • 179

3 Answers3

0

I use the method suggested in this answer:

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}
Community
  • 1
  • 1
Raffaele
  • 20,337
  • 5
  • 45
  • 86
0

You can use regexp for example :

function is_number(n) {
   return (/^-?\d[0-9.e]*$/).test(n);
}
OneOfOne
  • 88,915
  • 19
  • 172
  • 173
0

isNaN() is definitely available in node.js.

!isNaN(+n)

The unary plus operator is my personal choice; won't catch your "- 22" example, but you could use !isNaN(+n.replace(/\s/g, "") to strip spaces.

cjohn
  • 10,730
  • 3
  • 29
  • 17