How to check if a string contains at least one number using regular expression (regex) in JavaScript?

February 11, 2021 - 2 min read

To check if a string contains at least one number using regex, you can use the \d regular expression character class in JavaScript.

  • The \d character class is the simplest way to match numbers.
// Check if string contain atleast one number 🔥
/\d/.test("Hello123World!"); // true

To get a more in-depth explanation of the process. Read on 📖.

Consider we have a string with some numbers Hello12345World! like this,

// String with some numbers
const str = "Hello12345World!";

Now let's write the regex by wrapping the \d character class inside regular expression delimiters like this /\d/.

// String with some numbers
const str = "Hello12345World!";

// Regular expression
const regex = /\d/;

At last, we can use the test() method in the regular expression and pass the string as an argument to the method to test if the string contains at least one number. It can be done like this,

// String with some numbers
const str = "Hello12345World!";

// Regular expression
const regex = /\d/;

// Check if string contians numbers
const doesItHaveNumber = regex.test(str);

console.log(doesItHaveNumber); // true
  • The method returns boolean true if present and false if not.

See the example live in JSBin.

Feel free to share if you found this useful 😃.