Tags
Asked 2 years ago
16 Jun 2021
Views 297
Jalon

Jalon posted

Count the number of integers in a string in JavaScript

Count the number of integers in a string
Phpworker

Phpworker
answered Apr 27 '23 00:00

To count the number of integers in a string in JavaScript, you can use a regular expression along with the match() method. Here's an example:



const str = "This is a string with 123 and 4567 in it.";
const integers = str.match(/\d+/g);
const count = integers ? integers.length : 0;
console.log(count); // Output: 2

In this example, the regular expression /\d+/g matches one or more digits (\d+) globally (g) in the string. The match() method returns an array of all the matches, which we assign to the integers variable. We then check if integers is truthy (i.e. not null or undefined) , and if so, we get its length to determine the number of integers in the string.
Post Answer