How to Check If a String Is a Number in JavaScript

Learn about the three best ways to check if a string is a number in JavaScript, and when to use each.

Published Categorized as JavaScript

There are a number of ways to check if a string is actually a number in JavaScript. However, the best ones involve the use of built-in JavaScript functions that let you do this quickly and reliably.

In this tutorial, I will walk you through my favorite ways to check if a string is a number: using the isNaN() function, using the Number() function, as well as with regular expressions.

I’ll also walk you through the pros and cons of each so you can decide for yourself which one to use.

Using the isNaN() Function

In JavaScript, when you try to perform a mathematical calculation or parsing operation on a value that’s expected to be a number but that turns out not to be, your function will return NaN—a special value that stands for “Not a Number.”

There’s also a built-in JavaScript function, called isNaN(), that lets you test if a given value is not a number. The function returns a boolean of true to indicate that the value being tested is not a number or false to indicate that it is a number.

You can read more about NaN here and more about isNaN() here.

Here’s how it works:

isNaN("123"); // false
isNaN("abc"); // true
isNaN("123abc"); // true

Edge cases and false positives:

However, it’s important to note that the isNaN() function returns false positives if given an empty string (""), a whitespace string (" "), a null value (null), or a boolean value (true or false) as an argument:

isNaN(""); // false
isNaN(" "); // false
isNaN(null); // false
isNaN(true); // false
isNaN(false); // false

If you want your code to handle these edge cases and not return false positives when given these arguments, you will need to implement extra conditional checks.

You can handle these edge cases by checking if the value you are about to test with isNaN() is not an empty string, a whitespace string, a null value, or a boolean value before actually calling isNaN().

Here is a function that implements these extra checks:

function isStrictlyNumeric(val) {
    if(val === "" || val === " " || val === null || typeof val === 'boolean') {
        return false;
    }
    return !isNaN(val);
}

console.log(isStrictlyNumeric("123")); // true
console.log(isStrictlyNumeric("abc")); // false
console.log(isStrictlyNumeric("123abc")); // false
console.log(isStrictlyNumeric("")); // false
console.log(isStrictlyNumeric(" ")); // false
console.log(isStrictlyNumeric(null)); // false
console.log(isStrictlyNumeric(true)); // false
console.log(isStrictlyNumeric(false)); // false

Keep these in mind and decide if and how you need to handle these edge cases in your code.

Using the Number() Function

Much like the isNaN() function, the Number() function is another practical method you can use to verify whether a string is a number in JavaScript. This function tries to convert its argument into a number and then returns the numerical value if it succeeds, or NaN if it fails.

This is how it works:

Number("123"); // 123
Number("abc"); // NaN
Number("123abc"); // NaN

As the above examples shows, Number("123") returns 123 because “123” can be converted into a number, while Number("abc") and Number("123abc") both return NaN because “abc” and “123abc” cannot.

Despite its usefulness, the Number() function also returns certain false positives when it deals with an empty string (“”), a whitespace string (” “), a null value (null), or a boolean value (true or false) as an argument:

Number(""); // 0
Number(" "); // 0
Number(null); // 0
Number(true); // 1
Number(false); // 0

To address these edge cases and prevent such false positives, you need to implement additional conditional checks in your code:

function isStrictlyNumeric(val) {
    if(val === "" || val === " " || val === null || typeof val === 'boolean') {
        return false;
    }
    return !isNaN(Number(val));
}

console.log(isStrictlyNumeric("123")); // true
console.log(isStrictlyNumeric("abc")); // false
console.log(isStrictlyNumeric("123abc")); // false
console.log(isStrictlyNumeric("")); // false
console.log(isStrictlyNumeric(" ")); // false
console.log(isStrictlyNumeric(null)); // false
console.log(isStrictlyNumeric(true)); // false
console.log(isStrictlyNumeric(false)); // false

Using Regular Expressions (RegEx)

For those who want to implement a more precise and explicit check, regular expressions, often abbreviated as RegEx, offer another approach to determine whether a string is a number in JavaScript.

Regular expressions are patterns used to match character combinations in strings. In this case, we can design a RegEx pattern that matches only numerical strings.

/^\d+$/.test("123"); // true
/^\d+$/.test("abc"); // false
/^\d+$/.test("123abc"); // false

Unlike the isNaN() and Number() functions, RegEx doesn’t return false positives when it comes to empty strings, whitespace strings, null values, and boolean values:

/^\d+$/.test(""); // false
/^\d+$/.test(" "); // false
/^\d+$/.test(null); // false
/^\d+$/.test(true); // false
/^\d+$/.test(false); // false

How to Decide Which Method to Use

When determining which method to use to check if a string is a number in JavaScript, it’s essential to consider the specific requirements of your project, your personal preferences, as well as performance implications.

isNaN();

If your project requires a simple and fast method that’s easy to understand and use, isNaN() might be the right choice for you.

It’s worth noting, however, that this method has limitations and may return false positives for empty strings, whitespace strings, null values, and boolean values.

Although you can add extra conditional checks to handle these edge cases, this does slightly increase the complexity of the method.

Number();

This method provides more explicit conversion of the input into a number.

While it’s similarly quick and simple, it shares the same limitations as isNaN() in terms of handling certain special values.

Again, these edge cases can be addressed with additional conditional checks.

RegEx

If you need a more flexible and explicit method that allows you to specify a pattern for the numerical strings, RegEx is the way to go.

Unlike the first two methods, it doesn’t consider empty strings, whitespace strings, null values, or booleans as numbers by default, which can be an advantage.

However, keep in mind that RegEx can be somewhat harder to grasp if you’re not familiar with it, and the performance can be a bit slower compared to the other two methods, especially for larger strings.

By Dim Nikov

Editor of Maker's Aid. Part programmer, part marketer. Making things on the web and helping others do the same since the 2000s. Yes, I had Friendster and Myspace.

Leave a comment

Your email address will not be published. Required fields are marked *