Check if String is a Valid Number in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 16, 2021

banner

Photo from Unsplash

Check if String is a Valid Number #

To check if a string is a valid number:

  1. Check that the string is not an empty string or contains only spaces.
  2. Pass the string to the isNaN() function.
  3. If isNaN returns false, the string is a valid number.
index.js
const str1 = '5'; const str2 = '5.5'; const str3 = ' '; const str4 = '123hi'; function isNumber(str) { if (typeof str !== 'string') { return false; } if (str.trim() === '') { return false; } return !isNaN(str); } console.log(isNumber(str1)); // 👉️ true console.log(isNumber(str2)); // 👉️ true console.log(isNumber(str3)); // 👉️ false console.log(isNumber(str4)); // 👉️ false

We first check if the value passed to the function doesn't have a type of string, in which case we return false straight away.

Then we check if the provided value is an empty string or contains only whitespace, in which case we also return false.

Finally, we use the isNaN function to check if the provided string is not a number.

We use the logical NOT (!) operator to negate the value returned from the isNaN function.

The isNaN (is not a number) function tries to convert the string into a number and if it fails, it returns true.

index.js
console.log(isNaN('hello')); // 👉️ true console.log(isNaN('')); // 👉️ false console.log(isNaN(' ')); // 👉️ false
This seems quite confusing at first, but the isNaN function converts an empty string or a string containing spaces to a number and gets a value of 0, so it returns false.
index.js
console.log(Number('')); // 👉️ 0 console.log(Number(' ')); // 👉️ 0

This is why we use the trim() method to trim the string and verify that it's not an empty string.

We know that if the isNaN function gets called with a string that contains at least 1 character and returns true, then the string is NOT a valid number.

Conversely, if the isNaN function gets called with a string that contains at least 1 character and returns false, then the string is a valid number.

Here are some more examples of calling isNaN with strings.

index.js
console.log(isNaN('123')); // 👉️ false console.log(isNaN('1.23')); // 👉️ false console.log(isNaN('1,23')); // 👉️ true console.log(isNaN('123test')); // 👉️ true

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.