Check if String is a Valid Number in JavaScript

avatar

Borislav Hadzhiev

Sat Oct 16 20212 min read

banner

Photo by Ben Eaton

Check if String is a Valid Number #

To check if a string is a valid number:

  1. Check if the string is not an empty string and does not contain only whitespace characters, in which case it's not a valid number.
  2. Pass the string to the isNaN() function. If the function 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) method 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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee