How to use isNaN() Function In Javascript
The isNaN()
function in JavaScript checks if a value is “Not-a-Number” (NaN). By converting a string to a number using parseFloat()
, it can determine if the string contains only digits. If the conversion is successful, it returns false
, indicating that the string contains only digits. Otherwise, it returns true
.
Example: The containsOnlyDigits
function checks if a string contains only digits by attempting to convert it to a number using parseFloat()
. It returns true
if successful, indicating the string contains only digits, otherwise false
.
function containsOnlyDigits(str) {
return !isNaN(str) && !isNaN(parseFloat(str));
}
console.log(containsOnlyDigits("123")); // Output: true
console.log(containsOnlyDigits("123abc")); // Output: false
Output
true false
How to check if string contains only digits in JavaScript ?
Checking if a string contains only digits in JavaScript involves verifying that every character in the string is a numerical digit (0-9).