+ 1
Js string
I have some string, for example a="1+2+3". Can we solve this task with js?
3 Answers
+ 4
Solve what task? You wanted to store a string and you did. If you want to do calculations on something, it needs to be numbers since that's what math uses. Strings may contain numbers, but the string itself is not a number, if you get what I mean.
https://code.sololearn.com/WWlnGZ0ZjN4p/#js
// When stored as a string
var a = "1+2+3";
document.write(a);
// OUTPUT::: 1+2+3
// When stored as a number
var b = 1+2+3;
document.write("<br>" + b);
// OUTPUT:::: 6
+ 3
If you have no option but to use a string, rather than using numbers from the start, then you'll need to extract the numbers and parse it for calculation. I use regex to extract the numbers into an array, and then I use a loop to do my calculations on it.
https://code.sololearn.com/WGBvqSE21uKA/#js
var a = "1+2+3";
var numsOnly = a.match(/(\d[\d\.]*)/g);
var sum = 0;
for (i = 0; i < numsOnly.length; ++i){
sum = sum + parseInt(numsOnly[i]);
}
document.write(sum);
// OUTPUT:::::: 6
0
I need to get value from the first string. It can changes in the program working.