How to find sum of integers in a string using JavaScript

后端 未结 3 1314
小蘑菇
小蘑菇 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 07:22

    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

提交回复
热议问题