Check if a string is a number in JavaScript

In this tutorial, I am going to show you how to check if a string is a number or not in JavaScript.

To check if a string is a number in JavaScript, there are several methods you can use, each with its own advantages. In this article, i am going to mention 4 different methods with examples to detect if a string is a number.

1. Using isNaN and parseFloat/parseInt

The first method involves parsing the string as a floating-point number (or an integer) and then checking if the result is NaN (Not a Number). If the value is Nan, that means it must be a number.

function isNumber(str) {
  return !isNaN(parseFloat(str)) && isFinite(str);
}

2. Using Regular Expression

The following method using regular expressions to check if a string strictly represents a number. Regular expressions can be tailored to your specific requirements (like allowing decimals or not).

function isNumber(str) {
  return /^[0-9]+(\.[0-9]+)?$/.test(str);
}

This regex checks for integers or decimal numbers. You can adjust the regex based on what you consider a valid number (e.g., including/excluding negatives, scientific notation, etc.).

3. With Number.isFinite

In this example, we are converting the string to a number using the Number constructor and then checking if it is a finite number.

function isNumber(str) {
  return Number.isFinite(Number(str));
}

4. Using + Unary Operator

The unary + operator attempts to convert the string to a number. Then you can check if the result is finite.

function isNumber(str) {
  return Number.isFinite(+str);
}

Each of these methods discussed above has different behaviors, especially when dealing with edge cases like strings containing only whitespace, special numeric values (like Infinity), or non-standard numeric formats. Choose the method that best fits for you.

Leave a Comment

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

Scroll to Top