ASD
ASD

Reputation: 735

Replace with the regular expression

What regular expression I need to use to correct

if (text.indexOf("+") != -1) {
            action = "+";
        } else if (text.indexOf("-") != -1) {
            action = "-";
        } else if (text.indexOf("*") != -1) {
            action = "*";
        } else if (text.indexOf("/") != -1) {
            action = "/";
        }

this code ?

EDIT:

and how can I improve this code:

switch (action) {
        case "+":
            result = parseInt(array[0]) + parseInt(array[1]);
            break;
        case "-":
            result = parseInt(array[0]) - parseInt(array[1]);
            break;
        case "*":
            result = parseInt(array[0]) * parseInt(array[1]);
            break;
        case "/":
            result = parseInt(array[0]) / parseInt(array[1]);
            break;
        default:
            break;
        }

Sorry for dull questions I am new in js.

Upvotes: 1

Views: 62

Answers (1)

Phrogz
Phrogz

Reputation: 303421

You can use either of these:

var action = text.replace(/.*([+*/-]).*/,'$1');

var match  = /[*+/-]/.exec(text);
var action = match && match[0];

If there's the possibility of newlines in your text then change the first to:

var action = text.replace(/[\d\D]*([+*/-])[\d\D]*/,'$1');

Edit: You can improve your switch statement by using, e.g.

// allow floating point values, and also 
// don't accidentally interpret "011" as octal
array[0]*1 + array[1]*1; 

For more details on why parseInt is probably bad, see this answer.

You can also remove the superfluous default section of your case statement. However, I suspect that your desired "improvement" was making fewer lines. Given that =-*/ are operators in JavaScript (and not methods), I cannot think of any way to avoid having four calculations (i.e. a switch or if/else if).

Whereas in Ruby you could, for example, use array[0].send(action,array[1]) to cover all four cases ;)

Upvotes: 4

Related Questions