I'm new to web development, and in my function want to check if a given string value is a number. In case the string isn't a valid number I want to return null.
The following works for all cases except when the string is "0" in which case it returns null.
parseInt(columnSortSettings[0]) || null;
How do I prevent this from happening. Apparantly parseInt doesn't consider 0 as an integer!
To check if a string contains numbers in JavaScript, call the test() method on this regex: /\d/ . test() will return true if the string contains numbers. Otherwise, it will return false .
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.
2) Using typeof() The typeof operator returns a string indicating the type of the unevaluated operand. If the variable is type number, it would return the string number . We can use this to determine if the variable is number type. The typeof() performs much better than isNaN() .
In JavaScript, a built-in method isNaN() evaluates the string in such a way that if the passed string is a number. This built-in function of JavaScript returns a true or false output based on the passing string. Furthermore, the “+” operator is employed to check the string by converting the string into a number.
Since 0
is act as false , so you can use isNaN()
in this case
var res = parseInt(columnSortSettings[0], 10);
return isNaN(res) ? null : res;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With