Question

I'm using JS / jQuery (new to jQuery) and I have a string with a math problem in it, including a variable. (I'm creating a function to solve basic algebra). ie:

var $problem = "x+5=11";
// Take off any whitespace from user input
$problem = $problem.replace(/\s+/g,"");
// Split problem into two parts
$problem = $problem.split("=");

Now I need to determine which part contains the variable. In this example it would be

$problem[0] // This stores "x+5"

What i'm stuck at is that the variable could be any letter, not just x, so I can't just search for x. It could be: a, b, A, x, z, Y.

Was it helpful?

Solution

You can test for any variable which has an alphabet using the regex

if(/[a-zA-Z$][a-zA-Z$_0-9]*/.test($problem[0])){
    //left part has a variable
}

OTHER TIPS

'x+5'.split(/[\W]+/g)

'xyx-2a*yb+5'.split(/[\W]+/g)

You can check if a string has a alphabet in it or not as following:

    var str = "x+1";
    if (str.match(/[a-zA-Z]/g)) {
        alert("true");
        }
    else {

        alert("false");
    }

Hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top