0

What is the correct way to check if a string is valid number in javascript?

Normally we use isNaN(str), this works great in all cases but excepts,

Current behaviour:

isNaN("1") = false, is a number,
isNaN("1 ") = false, But this is a string.

What is the correct approach to deal with this?

Expected results:

isNotNumber("1") = false
isNotNumber("1 ") = true
Amin
  • 11
  • 3
  • 1
    Does this answer your question? [Why does isNaN(" ") (string with spaces) equal false?](https://stackoverflow.com/questions/825402/why-does-isnan-string-with-spaces-equal-false) – Sinan Yaman Jan 22 '21 at 10:39
  • It _should_ be false for both values. They both can be converted to a number successfully. – evolutionxbox Jan 22 '21 at 10:40

2 Answers2

0

That's a bit of an odd case. I don't know of any native JS solution for this, but you could do the following:

function isNotNumber(subj: string): boolean {
  const nr = +subj;
  
  return isNaN(nr) || nr.toString().length !== subj.length;
}

example with tests

Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
0

I believe with Regular expressions you can achieve this easily

const isNotNumber = (value) => !/^\d+$/.test(value)

console.log(isNotNumber("1")) // false
console.log(isNotNumber(" 1")) // true
Owen Kelvin
  • 14,054
  • 10
  • 41
  • 74