How to check if a string is a number in JavaScript?

In this tutorial, we’re going to look at the different ways to check if a string is a number in JavaScript. Let’s first look at the main way of checking if a string is a number first, and then also look at ways of converting a string to a number, and then checking if the conversion is a NaN value or a valid number.

Use isNaN() to check if it’s a number

The easiest way of checking if a string is a number or not is by using the isNaN() method.

As the name implies, isNaN is used to check if a value is NaN (Not a Number) or not. If the method returns a true value, that means the value is NaN (was a string of letters before conversion). If it returns false, it means the value is a number (the string contained valid numbers and nothing else).

So, for the purpose of this tutorial, we’ll be looking for a ‘false’ result from isNaN. Once you get back the result, you can use an ‘if’ statement or a ternary operator to check what the result is and perform according to that.

The isNaN() method works with numbers (integers and floating point numbers) and returns a false value, with strings, where it returns a true value, or numbers within a string (where it converts the string to a number before checking it, and if the result is a valid number, it returns a false), as shown in the examples below:

console.log(isNaN(4)); //false - number
console.log(isNaN('apple')); //true - not a number
console.log(isNaN('456')); //false - number 

Use parseInt or Number or parseFloat to convert the string to number

As I mentioned in the introduction, to check whether a string is a number, it is always good to convert the string to a number first, so you can use it for calculations. Let’s look at the different ways of doing that now.

Sometimes, strings would just contain number inside of them, so basically, they’ll just be numbers inside quotes, like ‘123’.

In those cases, you can easily convert them to integer or floating point (numbers with decimal points) by using certain pre-defined JavaScript methods.

The simplest way to convert a string to number is by using the parseInt method. As the name implies, this method converts a string into an integer value, that is, a whole number.

let num = '123';
num = parseInt(num); //123 

You can also use the Number() method to achieve the same result. Since this tutorial focuses on checking whether a string is a number, we’ll not be going into detail on these methods.

num = Number(num); 

Finally, we have the parseFloat() method, which, as the name implies, can be used to convert a string to a floating point number.

num = parseFloat(num); 

The great thing with parseInt or parseFloat is that numbers followed by characters will also be considered numbers.

That is, if the string has ‘123ab’ in it, since the string starts with numbers, on using the parseInt or parseFloat method on it, we’ll get back a 123 or 123.00, because it’ll ignore the trailing letters and just extract the leading numbers, as shown below:

let num = '123ab';
num = parseInt(num); //123 

Now that you know how to convert strings to numbers, let’s look at how to check if the result of the conversion is actually a number, or a NaN value.

Use parseInt or Number or parseFloat with isNaN()

The simplest way to check if the result of a string to number conversion is a valid number is by using the isNaN() method, as shown in the example below:

let num = '123';
num = parseInt(num); //123
console.log(isNaN(num)); //false 

Once you get back a result, you can use any of the conditional statements to perform operations based on the result.

Also, as far as your isNaN method is concerned, number(s) mixed with letters (characters) will still be considered a string. It doesn’t truncate the leading numbers like parseInt or parseFloat does.

So, if you’re not sure about your result, you’re better off using parseInt or parseFloat first, and then using isNaN on the result of the conversion.

console.log(isNaN('45ab')); //true - not a number – false positive  

One more thing to look out for is that isNaN converts spaces, and even an empty string, to 0, so you’ll assume these are numbers after the check, when they’re not.

So, to avoid encountering false positives, make sure you use the trim() method on your string to trim leading and trailing extra spaces beforehand.

console.log(isNaN('')); //false - converts to 0 - use trim
console.log(isNaN(' ')); //false - converts to 0 - use trim
console.log(isNaN('    ')); //false - converts to 0 - use trim 

Checkpoints to look out for

You might think that the easiest way to check whether the result of parseInt() is a number is by comparing the result to NaN using an ‘if’ statement, but that’s where you’re wrong.

JavaScript is a complicated language and has a lot of pitfalls you need to look out for. NaN comparison is one such pitfall.

Unfortunately, in JavaScript, comparing 2 NaN values will always result in ‘false’, regardless of which comparison operator you use (== or ===), as shown in the example below:

if(NaN === NaN) {
    console.log('Equal');
}

else {
    console.log('Not equal'); //result is 'Not equal'
} 

So, once you convert a string to a number, use isNaN() on it to check it, and refrain from using comparison operators.

Also, you might be tempted to check the type of the converted value. You might think that the typeof NaN is something else (object or NaN), and as long as you get back ‘number’ as a result of the check, you can be sure that you have a valid number in your hand, but again, you’re wrong.

The type of NaN is also a number, and if you try to find if the result of a conversion is a number by checking its type, you’ll again end up with false positives.

console.log(typeof NaN); //Number 

Unary plus (+) operator

Yet another great way to convert a string to a number is by placing the unary plus operator right before it, as shown below:

console.log(+'123'); //123
console.log(+'Hello'); //NaN
console.log(+'-123'); //-123
console.log(+''); //0 - check for empty string beforehand
console.log(+' '); //0 - use trim beforehand 

let num = '2355';
console.log(isNaN(num)); //false 

As you can see above, the unary + operator works on both positive and negative numbers within strings. It returns NaN if a string contains just letters.

It returns false positives (0 value) for empty strings, just like the parseInt method does, so use trim() on the string beforehand, as discussed before.

Once you’ve converted the string, you can use isNaN to check the result of the conversion, as we’ve seen before.

Use regular expressions and the test() method

Also, use regular expressions to check if a string contains just numbers or not. You can modify the regular expressions to test for different conditions. Let’s look at some.

To start with, if you’d like to check if the string contains an integer number (just numbers and no characters in between), use this condition: /^\d$/ where

• ^ (carat symbol) stands for the start of the string,
• \d is the digits flag and represents [0-9],
• and \d+ means there can be 1 or more (meaning, there has to be at least 1 digit in the string),
• and $ stands for the end of the string.

We’re basically asking the test method to check if the string starts and ends with valid digits (0 to 9).

The test method tests the regular expression (given before the period) with the string you’ve placed inside the brackets (argument), and if the string matches the regular expression’s condition, it’ll return ‘true’.

const checkIfNumber = (num) => {
    return /^\d+$/.test(num);
}

console.log(checkIfNumber('abc')); //false
console.log(checkIfNumber('123')); //true
console.log(checkIfNumber(' ')); //false
console.log(checkIfNumber('')); //false 

In the above example, we’ve created a function to perform the test, so it can be used multiple times. You get back false for ‘abc’, which has only letters within the quotes, but surprisingly, you also get back false for empty strings and strings with just spaces.

You only get back ‘true’ when the string contains just numbers, and nothing else.

So, in conclusion, using regular expressions and the ‘test’ method is a better way of checking if a string is a number.

More complicated regular expressions

The above regular expression only works on positive integer values. If you’d like it to return true for either positive or negative values, then include -? right before the \d flag. ? refers to 0 or 1.

That is, it’ll return true regardless of whether ‘-‘ is present or not in the string, as shown below:

const checkIfNumber = (num) => {
    return /^-?\d+$/.test(num);
}

console.log(checkIfNumber('123')); //true
console.log(checkIfNumber('-123')); //true 

Now, if you’d like to check for either integer or floating-point numbers, you need to include conditions for an optional ‘.’, and more numbers after that.

.? will take care of the optional period, then right after that, include the \d flag followed by the * condition this time. ‘*’ refers to 0 or more, so even if you don’t have numbers after the ‘.’, you’re good to go.

You can modify this condition in any way you see fit based on your use cases.

const checkIfNumber = (num) => {
    return /^-?\d+.?\d*$/.test(num);
}

console.log(checkIfNumber('-123')); //true
console.log(checkIfNumber('-123.56')); //true 

Also, you can use [0-9] instead of \d and the regular expression will work the same, as shown below:

/^-?[0-9]+.?[0-9]+$/.test(num); 

The string match methods works perfectly with regular expressions as well. The only difference between ‘test’ and ‘match’ is its syntax, and the type of result they both return, as shown below:

Boolean(num.match(/^-?[0-9]+.?[0-9]+$/)) 

Match returns an object with the matched string as a part of it, so make sure to convert the result to Boolean. If an object is returned at all, you’ll get back ‘true’ as a result of the conversion; otherwise, you’ll get back ‘false’.

That’s it! In this tutorial, we’ve looked at 4 different ways of converting a string to a number (parseInt, Number, parseFloat, unary plus) and 2 different ways of checking whether a string is a number or not (isNaN and regular expressions with test() or match()).

Leave a Comment