DEV Community

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

Posted on • Originally published at melvingeorge.me

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

Originally posted here!

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
Enter fullscreen mode Exit fullscreen mode

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!";
Enter fullscreen mode Exit fullscreen mode

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/;
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
  • 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 ๐Ÿ˜ƒ.


Top comments (1)

Collapse
 
codingpanel profile image
Coding Panel

We try to determine whether the string we are trying to check contains only entirely numeric characters using the regular expression / [0-9] + $ /. The character "/" serves as the expression's separator at both the beginning and finish, according to an analysis of this expression. It's crucial to be aware that other delimiters, such as (),, [], >, or #, can be used as start and end delimiters. For instance: # [0-9] + $ # . Worth reading link Javascript check if string contains only numbers