Pick out numbers from a string

Let’s say I have a string, something like this:

sadasd4assadasd8ssssda5asadasd3asdasdasd8dsdsd

and I want to pick out the numbers and add them to each other. How do I do that? I have tried and know how to pick out one number, but how do I pick out several numbers and add them?
Many thanks

var results = string.match(“regex”);

alert(results[entry number you wish to access]);

By using preg_match_all to get all matches for digits, and [url=“http://nz.php.net/manual/en/function.array-sum.php”]array_sum to add them together.


$str = 'sadasd4assadasd8ssssda5asadasd3asdasdasd8dsdsd';
preg_match_all('/\\d+/', $str, $matches);
$sum = array_sum($matches[0]);
// $sum is 28

Oh hang on, this isn’t the PHP forum. Back shortly with a valid solution.


var str = 'sadasd4assadasd8ssssda5asadasd3asdasdasd8dsdsd';
var sum  = 0;
str.match(/\\d+/g).forEach(function(num) {
    sum += Number(num) || 0;
});
// sum is 28

forEach isn’t quite ripe yet (in javascript), pmW-

might have to do it the long way-

var str = 'sadasd4assadasd8ssssda5asadasd3asdasdasd8dsdsd';
var sum  = 0;
str=str.match(/(\\.d+)|(\\d+(\\.d+)?)/g) || [];
while(str.length) sum+=parseFloat(str.shift())

Unfortunately in IE you get ‘object doesn’t support this property or method.’

The same goes for str.match(/\d+/g).map(…

Alternative

var str = 'sadasd4assadasd8ssssda5asadasd3asdasdasd8dsdsd';
matches = str.match(/\\d+/g);
var sum = 0;
for (var i = 0, l = matches.length; i < l; i +=1){
	sum += Number(matches[i]);
}
alert(sum);

I liked the idea of Array_sum though

Array.sum = function (matches){
	if (!(matches instanceof Array)) { throw new Error("Array.sum requires an Array"); }
	var sum = 0, l = matches.length;
	while (l--){ sum += Number(matches[l]); }
	return sum;
}

alert(Array.sum(matches));

I advise learning regular epressions.


 
<script type="text/javascript">

var str = 'The Time Through Ages. In the Name of Allah, Most Gracious, Most Merciful. 1.By the Time, 2.Verily Man is in loss, 3. Except such as have Faith, and do righteous deeds, and (join together) in the mutual enjoining of Truth, and of Patience and Constancy.';
var num=str.split(/\\D+/g);
for(var i=1, sum=0; i<num.length;i++) sum += Number(num[i]);
alert(sum);

</script>

Thank you!

Lets say I have these numbers:

2,4,5,6,7,6

Is it possible to pick out only the two number six and add them to twelve?

This is the compatibility code for Array.sum


Array.prototype.sum = function() {
    var i, sum;
    for (i = 0, sum = 0; i < this.length; sum += this[i++]);
    return sum;
}

This is the compatability code for Array.filter


if (!Array.prototype.filter)  
{  
  Array.prototype.filter = function(fun /*, thisp*/)  
  {  
    var len = this.length >>> 0;  
    if (typeof fun != "function")  
      throw new TypeError();  
  
    var res = [];  
    var thisp = arguments[1];  
    for (var i = 0; i < len; i++)  
    {  
      if (i in this)  
      {  
        var val = this[i]; // in case fun mutates this  
        if (fun.call(thisp, val, i, this))  
          res.push(val);  
      }  
    }  
  
    return res;  
  };  
} 

Once you have those, it’s a simple matter of:


function isASix(num) {
    return num === 6;
}

numbers = [2,4,5,6,7,6];
var total = numbers.filter(isASix).sum();
// total is 12


<script type="text/javascript">


var num= [2,4,5,6,7,6];

for(var i=0, sum=0; i<num.length; i++) {

if(num[i]==6) {  sum +=num[i]; }

}

alert(sum); // 12

</script>



 
 
<script type="text/javascript">

var num= [2,4,5,6,7,6];

for(var i=0, sum=0; i<num.length; (num[i]==6 ? (sum +=num[i++] ) : num[i++]) );

alert(sum); // 12


</script>

pmw,
thanks for this line:
for (i = 0, sum = 0; i < this.length; sum += this[i++]);

This is the compatability code for Array.filter

That’s handy pwm57

I see there’s also Array.forEach compatibility code

Just a thought, but if these numbers were being pulled out of a string and using PWM’s sum method with parseFloat added.

Array.prototype.sum = function() {
    var i, sum;
    for (i = 0, sum = 0; i < this.length; sum += parseFloat(this[i++])); // parseFloat to convert the strings to numbers
    return sum;
}

var strg = "sadasd4assadasd6ssssda5asadasd6asdasdasd8dsdsd"

var total = strg.match(/[6]/g).sum(); // just sixes
var total2 = strg.match(/[46]/g).sum(); // fours and sixes
alert (total); //12
alert (total2); //16

Thank you very much, all of you for your help! Much appreciated!