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 andfalse
if not.
See the example live in JSBin.
Top comments (1)
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