1
parseInt('5aab4') //5
// I expect the output is NaN.

My logic fails, due to parseInt. I assume that parseInt always returns NaN, when the input contains a letter?

Henok Tesfaye
  • 6,590
  • 11
  • 33
  • 66
  • 3
    *"I assume that parseInt always returns NaN, when the input contains a letter"* - Don't assume, verify: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt You also may find some responses here useful: https://stackoverflow.com/questions/175739/built-in-way-in-javascript-to-check-if-a-string-is-a-valid-number – David Apr 25 '19 at 20:12
  • 1
    Indeed, from the documentation: "If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point" –  Apr 25 '19 at 20:15
  • @ScottMarcus. I don't think it's a duplicate. My question is not how parseInt() works rather another option to check if a string only contains a number. – Henok Tesfaye Apr 25 '19 at 20:23
  • 1
    You make no mention of another option in your question. You say *I assume that parseInt always returns NaN, when the input contains a letter?* which indicates you are asking about how `parseInt()` works. In fact, no where in the entire question do you even use the words *"check if a string only contains a number"*. – Scott Marcus Apr 25 '19 at 20:29

2 Answers2

3

No, parseInt() allows "garbage" (non-number) characters after some numeric characters. The parseFloat() function has the same "feature".

If you want to get a number, you can use Number("123") or simply the + unary operator. However those accept any JavaScript number, including ones with fractional parts or numbers in scientific notation. But those methods will fail and give NaN if the string input is not a valid numeric constant.

You could do something like

if (+someString === Math.floor(+someString))

I guess.

edit — a comment notes that you'd also want to check the degenerate case of an empty or all-space string too. A simple regular expression (/^\d+$/) followed by a sanity check that it's not 200 digits long (amonth possibly other things) is another alternative.

Pointy
  • 389,373
  • 58
  • 564
  • 602
-1

If you were wanting to check NaNanother way would be to test it with isNaN(). isNaN() will return a boolean giving you a verification for a given input.

parseInt('5aab4') //5

isNaN('5aab4') // true
Bryan
  • 274
  • 3
  • 9