Check if String contains at least one Number in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 20 20212 min read

banner

Photo by Pavel L

Check if String contains Numbers #

To check if a string contains numbers, call the test() method on a regular expression that matches all numbers, passing it the string as a parameter. The test method will return true if the string contains numbers, 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 / / denote the start 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. It's by far the best one out there.

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

An alternative is to use a range, which may be more readable if you're not familiar with the special characters in regular expressions.

The following example achieves the same goal.

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 character \d, we used a character class [0-9].

We specified a range of numbers we want to match 0-9.

This is a bit more direct and easier to read than using the \d character and it matches the exact same digits.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee