'Count the number of integers in a string
how can I count the number of integers in a string using jQuery or javascript?
For example g66ghy7 = 3
Solution 1:[1]
Solution 2:[2]
I find this to look pretty/simple:
var count = ('1a2b3c'.match(/\d/g) || []).length
A RegExp will probably perform better (it appears):
var r = new RegExp('\\d', 'g')
, count = 0
while(r.exec('1a2b3c')) count++;
Solution 3:[3]
The simplest solution would be to use a regular expression to replace all but the numeric values and pull out the length afterwards. Consider the following:
var s = 'g66ghy7';
alert(s.replace(/\D/g, '').length); //3
Solution 4:[4]
A little longer alternative is to convert each char to a number; if it doesn't fail, raise the counter.
var sTest = "g66ghy7";
var iCount = 0;
for (iIndex in sTest) {
if (!isNaN(parseInt(sTest[iIndex]))) {
iCount++;
}
}
alert(iCount);
Also see my jsfiddle.
Solution 5:[5]
Short and sweet:
str.match(/\d/g)?.length || 0
Thanks to @CertainPerformance answer here
const str = 'g66ghy7'
const digitCount = str.match(/\d/g)?.length || 0;
console.log('digitCount', digitCount)
Solution 6:[6]
A simple for can solve this:
const value = "test:23:string236";
let totalNumbers = 0;
for (let i = 0; i < value.length; i++) {
const element = value[i];
if (isFinite(element)) {
totalNumbers++;
}
}
console.log(totalNumbers);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Petar Ivanov |
Solution 2 | Ricardo Tomasi |
Solution 3 | |
Solution 4 | |
Solution 5 | danday74 |
Solution 6 | Iglesias Leonardo |