更新时间:2023-02-19 12:36:10
var patrn = \\D; // this is the regular expression that removes the letters
这不是JavaScript中的有效正则表达式.
This is not a valid regular expression in JavaScript.
您还缺少代码结尾的右括号.
You are also missing a closing bracket in the end of your code.
一种更简单的解决方案是找到字符串中的所有整数,将它们转换为数字(例如,使用+
运算符)并将它们求和(例如,使用reduce
运算符).
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