regex - Arithmetic operations inside the parenthesis javascript -


hi please me resolve issue

    var str = '10+20-10-2';     var numbers = str.replace(/ /g, '').split(/[-+*\/]/g);     var operators = str.replace(/ /g, '').split(/\d*/g);     operators.shift();             var result = +numbers[0];             (var = 0; < operators.length - 1; i++) {         result = eval( result + operators[i] + numbers[i + 1] );     }             alert(result)​; 

above code working fine , when trying pass other input

 var str = '-(1)-(-2)';     var str = '-1-(-1)';     var str = '(-1)-2'  ;  

not getting result

i guess in case, besides eval, use

var result = parsefloat(numbers[0]); 

and consequently

result = eval( result + operators[i] + parsefloat(numbers[i + 1])) 

this bit more solid because works if strings in numbers contain numbers, , return nan if don't. also, more solid, go long way , use switch instruction:

switch(operators[i]) {    case "+":    etc. } 

of course solution more elegant, since not work reason, might spot it. in you, i'd check couple alert() functions actual content of splitted arrays. regular expressions not produce quite output you'd expect them to.


Comments

Popular posts from this blog

android - Why am I getting the message 'Youractivity.java is not an activity subclass or alias' -

Making Empty C++ Project: General exception (Exception from HRESULT:0x80131500) Visual Studio Community 2015 -

How to fix java warning for "The value of the local variable is not used " -