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.

JavaScript
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).

Similar Reads

1. Using Regular Expression

Regular expressions (regex) are patterns used to match character combinations in strings. In JavaScript, they are typically defined between forward slashes /, like /pattern/. To check if a string contains only digits, you can use the regex pattern ^\d+$....

2. Using isNaN() Function

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....

3. Using Array.prototype.every()

The Array.prototype.every() method tests whether all elements in the array pass the test implemented by the provided function. We can split the string into an array of characters and check if every character is a digit....