Check if String contains at least one Number in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Check if String contains Numbers #

Use the RegExp.test() method to check if a string contains at least one number, e.g. /\d/.test(str). The test method will return true if the string contains at least one number, otherwise false will be returned.

index.js
const str1 = 'hello 42 world'; const str2 = 'hello world'; function containsNumber(str) { return /\d/.test(str); } console.log(containsNumber(str1)); // 👉️ true console.log(containsNumber(str2)); // 👉️ false

We used the RegExp.test method to check if the string contains numbers.

The forward slashes / / mark the beginning and end of the regular expression.

The \d character matches any digit from 0 to 9.

If you ever need help reading a regular expression, check out this regex cheatsheet from MDN.

The test() method returns true if the regular expression is matched in the string, otherwise false is returned.

Alternatively, you can use the [0-9] range. This may be more readable if you're not familiar with the special characters in regular expressions.

The following example also checks if a string contains at least one number.

index.js
const str1 = 'hello 42 world'; const str2 = 'hello world'; function containsNumber(str) { return /[0-9]/.test(str); } console.log(containsNumber(str1)); // 👉️ true console.log(containsNumber(str2)); // 👉️ false

Instead of using the \d special character, we used the [0-9] character class.

This character class is used to specify a range of numbers that we want to match.

The [0-9] range should be a bit more readable than the \d character if you aren't familiar with regular expressions.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.