How to find sum of integers in a string using JavaScript

后端 未结 3 1315
小蘑菇
小蘑菇 2021-01-29 06:43

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 m

3条回答
  •  被撕碎了的回忆
    2021-01-29 06:58

    you have some errors :

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

    use parseInt : total += parseInt(tot);

    function sumofArr(arr){ // here i create a function that has one argument called arr
    var 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 integers
    var patrn = "\\D"; // this is the regular expression that removes the letters
    var 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/

提交回复
热议问题