1

I want to test a regular expresion like this: 213+123, a number plus + plus a number. This is de code:

var re = /\d+[+]\d+/
result = window.eval(command);
var bool = re.test(result);

The code respond false if I try to enter 234+234. Any help

4
  • Your regex is True seems that the problem is because of your functions Commented Jul 20, 2015 at 21:23
  • 4
    Shouldn't it be re.test(command)? If you eval 213+123, you get back the result of the expression, which is a single number. Commented Jul 20, 2015 at 21:23
  • 1
    Just a note that using eval is not safe with user input. I have written a sumup function that does the parsing in a safer manner. Commented Jul 20, 2015 at 21:53
  • @stribizhev: evaling the user's own input is not unsafe... after all, they could also just type the code in the console. Commented Jul 21, 2015 at 17:55

1 Answer 1

1

The problem is not the regex but the eval.

var command = "234+234";
var result = window.eval(command); // result will be 468 so the regex will fail
var bool = re.test(result); // equals re.test(468);

Instead call it on the command

var command = "234+234";
var bool = re.test(command); // equals re.test("234+234");
Sign up to request clarification or add additional context in comments.

1 Comment

I trying to evaluate the result, no the expresion. Thanks'alls

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.