How to Check if a String is a Number in JavaScript
  John Mwaniki /   21 Dec 2023

How to Check if a String is a Number in JavaScript

In this article, you will learn different techniques for checking if a string is a number in JavaScript, with the help of multiple examples.

As a developer, you will often need to verify whether a string is a number in various scenarios. Below are some of the common instances where this is applicable:

  • User Input Validation: When accepting user input, especially in forms, it's crucial to validate whether the entered value is a valid number. This prevents unexpected behaviors and ensures the application works as intended.
  • Data Processing: When working with external data, such as reading from a file or receiving data from an API, it's essential to verify that the incoming strings can be safely converted to numeric values.
  • Mathematical Operations: Before performing mathematical operations on a value, it's necessary to check if the variable is a valid number to avoid errors and unexpected results in calculations.

Methods for Checking if a String is a Number

JavaScript offers several methods to check if a string is a numerical value. In this article, we will cover two of them:

1. Using isNaN() Function

The isNaN() function checks if a value is NaN (Not a Number). It returns true if the value is not a number, otherwise false.

Example 1

var str = "3.14";

if (isNaN(str)) {
    console.log("The string is not a number");
}
else {
    console.log("The string is a number");
}

Output:
The string is a number

Example 2

var str = "Hello World!";

if (isNaN(str)) {
    console.log("The string is not a number");
}
else {
    console.log("The string is a number");
}

Output:
The string is not a number

2. Using Regular Expressions

Regular expressions offer a powerful way to validate strings. The following example uses a regular expression to check if a string is a valid number.

Example 1

var str = "102";

if (/^-?\d+(\.\d+)?$/.test(str)) {
    console.log("The string is a number");
}
else {
    console.log("The string is not a number");
}

Output:
The string is a number

Example 2

function numValidator (str) {
    if (/^-?\d+(\.\d+)?$/.test(str)) {
        return str + " is a number";
    }
    else{
        return str + " is not a number";
    }
}

console.log(numValidator("89"));
console.log(numValidator("3.14"));
console.log(numValidator("JavaScript"));

Output:
89 is a number
3.14 is a number
JavaScript is not a number

Key Considerations

  • Empty Strings: Consider how to handle empty strings based on your application's logic.
  • Whitespace: Trim leading/trailing whitespace before validation if necessary.
  • Number Formats: Adjust regular expressions to accommodate specific number formats (e.g., with commas or currency symbols).