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 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));
<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>
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
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