[英]How to calculate digit containing in string in javascript?
I have a function and I want to calculate digit that contains in a string. 我有一个函数,我想计算字符串中包含的数字。
str='hel4l4o';
The code that I created: 我创建的代码:
function sumDigitsg(str) {
var total=0;
if(isNaN(str)) {
total +=str;
console.log(total);
}
//console.log(isNaN(str));
return total;
}
You can do this using regex to match all digits ( .match(/\\d+/g)
) and then use .reduce
to sum the digits matched: 您可以使用正则表达式来匹配所有数字(
.match(/\\d+/g)
),然后使用.reduce
来对匹配的数字求和:
const str = 'hel4l4o'; const total = str.match(/\\d+/g).reduce((sum, n) => sum + +n, 0); console.log(total);
As for your code, you need to loop through your characters and then check if it is a number using if(!isNaN(char))
. 对于您的代码,您需要遍历字符,然后使用
if(!isNaN(char))
检查它是否为数字。 After that you need to turn the character into a number by using something like the unary plus operator ( +char
) such that you can add it to total
: 之后,您需要使用一元加号运算符 (
+char
)将字符转换为数字,以便可以将其添加到total
:
let str = 'hel4l4o'; function sumDigitsg(str) { let total = 0; for(let i = 0; i < str.length; i++) { let char = str[i]; if (!isNaN(char)) { total += +char; } } return total; } console.log(sumDigitsg(str));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.