JavaScript Check if a String is a Number

By James L.

Knowing how to check if a string is a number in JavaScript is a fundamental skill for any web developer. It is useful in a variety of situations, such as when validating user input, performing mathematical calculations, and manipulating data.

In this guide, we’ll discuss the following approaches to checking if a string is a number in JavaScript:

  1. Using isNaN() function
  2. Using regular expression

Using isNaN() function

In JavaScript, NaN stands for “Not a Number”. It is a special value that represents an invalid number.

It is returned when an operation attempts to convert a non-numeric value to a number, or when a mathematical operation results in an undefined value.

The isNaN() function returns true if the value passed to it is not a valid number (NaN), and false otherwise.

For example:

console.log(isNaN("22")); // false
console.log(isNaN("hello")); // true

Now let’s write code that checks if the string is a number. The function below returns true if the string is a number and false otherwise.

function isNumber(str) {        
    // Check if the input is a string    
    if (typeof str !== "string") return false;    
    // Remove leading and trailing whitespace    
    str = str.trim();   
    // Check for empty string 
    if (str === "") return false;      
    // Check for valid number using isNaN()   
    return !isNaN(str);
}

console.log(isNumber("22"));  // true 
console.log(isNumber("abc")); // false
console.log(isNumber("3.45")); // true
console.log(isNumber("-35")); // true 
console.log(isNumber("2e5")); // true
console.log(isNumber(""));    // false
console.log(isNumber(" "));   // false
console.log(isNumber("12px")); // false
console.log(isNumber(NaN));   // false
console.log(isNumber(undefined)); // false

In the example above, we use the typeof operator to confirm that the variable str is indeed a string.

It is important to remove any extra whitespace characters using the trim() function and check for an empty string because isNaN() function returns false for empty string, even though an empty string is not a valid number.

The exclamation point (!) before the isNaN() function is a logical NOT operator. It negates the result of the isNaN() function. So the condition is true if str is a valid number and false if it’s NaN or not a number.

If you need to perform any mathematical calculations after determining that the string is a number, you can convert the string to a number using the Number() constructor. This will ensure that the string is treated as a numeric value and can be used in mathematical operations.

For example, if you have a string representation of a number, such as “22“, you can convert it to a number using Number() and then perform calculations on it:

const numString = "22";
const numValue = Number(numString);
console.log(numValue + 10); // Output: 32

Using regular expression

You can also use regular expressions to check if a string is a number

However, using regular expressions comes with potential drawbacks such as limited precision, complexity, false positives, internationalization issues, and potential performance impacts.

You should only use regular expressions if you know the exact format of the numbers you are dealing with.

In this guide, I will show you how to check for different kinds of numbers using regular expressions.

Checks if string is a whole number

Below is a function that returns true if the string is a whole number and false otherwise.

function isNumber(str) {    
    // Check if the input is a string    
    if (typeof str !== "string") return false;    
    // Remove leading and trailing whitespace    
    str = str.trim();    
    // Check for empty string    
    if (str === "") return false;    
    // Check for valid whole number using regular expression    
    return /^\d+$/.test(str);
}

console.log(isNumber("22"));    // true
console.log(isNumber("abc"));   // false
console.log(isNumber("3.14"));  // false
console.log(isNumber("-35"));   // false

The regular expression /^\d+$/ matches one or more occurrences of digits (0-9), ensuring that the string contains only whole numbers.

Here is a breakdown of the regular expression /^\d+$/:

Anchors:

^: Matches the beginning of the string

$: Matches the end of the string

Whole numbers

\d+: Matches one or more occurrences of digits (0-9)

Checks if a string is a whole number or decimal number

Below is a function that returns true if the string is a whole number or decimal number and false otherwise.

function isNumber(str) {    
    // Check if the input is a string    
    if (typeof str !== "string") return false;    
    // Remove leading and trailing whitespace    
    str = str.trim();    
    // Check for empty string         
    if (str === "") return false;    
    // Check for valid whole number or decimal number using regular expression    
    return /^\d*\.?\d+$/.test(str);
}

console.log(isNumber("22"));    // true
console.log(isNumber("abc"));   // false
console.log(isNumber("3.14"));  // true

The regular expression /^\d*\.?\d+$/ expands upon the previous one, allowing for an optional decimal point and one or more fractional digits. This captures both whole and decimal numbers.

Here is a breakdown of the regular expression /^\d*\.?\d+$/:

Anchors:

^: Matches the beginning of the string

$: Matches the end of the string

Whole number or decimal number:

\d*: Matches zero or more digits (0-9).

\.?: Matches an optional decimal point (.).

\d+: Matches one or more digits (0-9).

Checks if a string is a whole numbers, decimal numbers or scientific numbers

Below is a function that returns true if the string is a whole number, decimal number or scientific numbers and false otherwise.

function isNumber(str) {   
    // Check if the input is a string    
    if (typeof str !== "string") return false;    
    // Remove leading and trailing whitespace    
    str = str.trim();    
    // Check for empty string    
    if (str === "") return false;    
    // Check for valid number using regular expression    
    return /^[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$/.test(str);
}

console.log(isNumber("22"));    // true
console.log(isNumber("abc"));   // false
console.log(isNumber("3.14")); // true
console.log(isNumber("-35"));   // true
console.log(isNumber("2e5"));   // true
console.log(isNumber(""));      // false
console.log(isNumber(" "));     // false
console.log(isNumber("12px"));  // false
console.log(isNumber(NaN));     // false
console.log(isNumber(undefined));// false

The regular expression /^[-+]?\d*.?\d+(?:[eE][-+]?\d+)?$/ encompasses the most comprehensive range of number formats. It allows for optional signs, whole numbers, decimal points, fractional digits, and scientific notation.

Here is a breakdown of the regular expression /^[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$/:

Anchors:

^: Matches the beginning of the string

$: Matches the end of the string

Optional signs:

[-+]?: Matches an optional plus (+) or minus (-) sign

Optional Whole Numbers:

\d*: Matches zero or more occurrences of digits (0-9)

Decimal Point and Fractional Part:

\.?: Matches an optional decimal point (.)

\d+: Matches one or more occurrences of digits (0-9)

Optional Scientific Notation:

(?:[eE][-+]?\d+)?: This is a non-capturing group (?: ...) for the optional exponent part. Matches an optional scientific notation format

[eE]: Matches an “e” or “E

[-+]?: Matches an optional plus (+) or minus (-) sign

\d+: Matches one or more occurrences of digits (0-9)

This regular expression effectively captures a wide range of valid number formats, including:

Integers (e.g., 22, -35)

Decimals (e.g., 3.14, -12.5)

Numbers in scientific notation (e.g., 2e5, -6.34e-2)

Conclusion

As a JavaScript developer, your choice between isNaN() and regular expressions depends on the specific requirements of your task.

For general purpose validation, isNaN() provides a simple and efficient solution. However, when dealing with specific number formats or scientific notation, regular expressions offer the flexibility to match complex patterns.

By mastering both techniques, you’ll be well-equipped to tackle any scenario involving numerical strings in your JavaScript projects.