+ 5

Why doesn't the addition work with my method in Javascript ???

I tried to make a program to add two numbers in the same string together. With some strings like "2+3" it works, but with the string"100123+456" it outputs NaN. Here is the program : var addition = "1+12" var num1= parseInt(addition); var Length = num1.length ; var half=addition .substr(num1,Length); var num2 = parseInt (half); var solution = num1+num2; alert(solution); Please help

4th Mar 2019, 9:04 PM
Darko _007
Darko _007 - avatar
6 Respostas
+ 7
Darko _007 Take a look at the code here for options. https://code.sololearn.com/WAkXK6YeTeqD/?ref=app [UPDATE:] Basically, you can use the following: let expression = "100123+456"; let operands = expression.match(/^(\d+)\+(\d+)$/); let operandA= parseInt(operands[1]); let operandB = parseInt(operands[2]); console.log(operandA+operandB);
5th Mar 2019, 12:00 AM
David Carroll
David Carroll - avatar
+ 6
The problem is "+" cant be parsed in your string the string should contain digits but allows plus or minus at the beginning of the string, doing "-200" is ok this will parse giving you -200 as an integer.
4th Mar 2019, 9:53 PM
D_Stark
D_Stark - avatar
+ 5
I'd use RegEx for this. I can post a solution when I get a free chance. In the meantime, do some research and give it a go.
4th Mar 2019, 10:03 PM
David Carroll
David Carroll - avatar
+ 4
Darko _007 I've updated my original answer with the minimum code to do the job.
5th Mar 2019, 11:10 PM
David Carroll
David Carroll - avatar
+ 3
var len = num1.toString().length; var half = addition.substr(len);
4th Mar 2019, 9:24 PM
Diego
Diego - avatar
+ 1
David Carroll I don't know what RegEx is and I am not able to understand your whole Code (I am a beginner so don't kill me), but I saw in your solution that I can use "eval" to calculate an addition in a string.
5th Mar 2019, 10:03 PM
Darko _007
Darko _007 - avatar