I am new to JavaScript and currently understand two things about the parseInt() method:
parseInt("100") // gives 100
parseInt("2019@string") // gives 2019
However, why would parseInt("string@2019")
give NaN?
You can see the issue if you look at the W3Schools page for parseInt
:
If the first character cannot be converted to a number, parseInt() returns NaN.
This is why the following returns NaN
:
console.log(parseInt("O123"));
But if you have multiple numbers in a string, separated by a non-digit character, then it will not error - it'll just return the first number:
Only the first number in the string is returned!
console.log(parseInt("12b34"));
This information is also found in the MDN page for parseInt
:
If the first character cannot be converted to a number, NaN is returned.