Skip to content Skip to sidebar Skip to footer

How To Find Sum Of Integers In A String Using Javascript

I created a function with a regular expression and then iterated over the array by adding the previous total to the next index in the array. My code isn't working. Is my logic off?

Solution 1:

var patrn = \\D; // this is the regular expression that removes the letters

This is not a valid regular expression in JavaScript.

You are also missing a closing bracket in the end of your code.


A simpler solution would be to find all integers in the string, to convert them into numbers (e.g. using the + operator) and summing them up (e.g. using a reduce operation).

var str = "12sf0as9d";
var pattern = /\d+/g;
var total = str.match(pattern).reduce(function(prev, num) {
  return prev + +num;
}, 0);

console.log(str.match(pattern)); // ["12", "0", "9"]console.log(total);              // 21

Solution 2:

you have some errors :

change var patrn = \\D with var patrn = "\\D"

use parseInt : total += parseInt(tot);

functionsumofArr(arr){ // here i create a function that has one argument called arrvar total = 0; // I initialize a variable and set it equal to 0 var str = "12sf0as9d"// this is the string where I want to add only integersvar patrn = "\\D"; // this is the regular expression that removes the lettersvar tot = str.split(patrn) // here i add split the string and store it into an array with my pattern

arr.forEach(function(tot){ // I use a forEach loop to iterate over the array 
total += parseInt(tot); // add the previous total to the new total
})
return total; // return the total once finished
}

alert(sumofArr(["1", "2", "3"]));

https://jsfiddle.net/efrow9zs/

Solution 3:

functionsumofArr(str) {
 var tot = str.replace(/\D/g,'').split('');
   return  tot.reduce(function(prev, next) {
   returnparseInt(prev, 10) + parseInt(next, 10);
});}

sumofArr("12sf0as9d");

Post a Comment for "How To Find Sum Of Integers In A String Using Javascript"