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' -

python - How do I create a list index that loops through integers in another list -

c# - “System.Security.Cryptography.CryptographicException: Keyset does not exist” when reading private key from remote machine -