+ 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
6 Respuestas
+ 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);
+ 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.
+ 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.
+ 4
Darko _007 I've updated my original answer with the minimum code to do the job.
+ 3
var len = num1.toString().length;
var half = addition.substr(len);
+ 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.