Languages
[Edit]
EN

JavaScript - check if string contains any numbers

0 points
Created by:
Kenya-Spears
440

In this article, we would like to show you how to check if the string contains any numbers in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

const text = 'Example 123';

if (text.match(/\d+/g)) {
	console.log('The string contains a number.');
}

 

Practical example

In this example, we use match() method to check if the text string contains any numbers.

// ONLINE-RUNNER:browser;

const regex = /\d+/g;
const text = 'Example number: 23.';

if (text.match(regex)) {
	console.log('The string contains a number.');
}

Note:

The match() method used with /g flag returns all results matching the complete regular expression (regex). If nothing matches returns null.

References

  1. String.prototype.match() - JavaScript | MDN
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join