2

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.

Vince
  • 2,596
  • 11
  • 43
  • 76
  • you need to test for regex `/[a-zA-Z]+/` – Arun P Johny Apr 12 '13 at 06:10
  • I hate regex :( It confuses me. But if it's my only option, I must use it! – Vince Apr 12 '13 at 06:11
  • what do you want to do with `x+5`? probably you want separate it further to `x` and `5` again – Arun P Johny Apr 12 '13 at 06:12
  • @ArunPJohny Yeah, I have the steps for the function written down on paper, that's the next step after determining which part of the array has the variable. For example, I don't event want to try to split the 11 into another array because it only has the one number. – Vince Apr 12 '13 at 06:14
  • So you want to check whether LHS or RHS has a variable right? – A J Apr 12 '13 at 06:14
  • @AJ Yes. I know how to check if the variable was 'x' all the time, but since it's based on user input, the variable can change. – Vince Apr 12 '13 at 06:16
  • that means first you need to find out whether the LHS/RHS has a variable. it can be done via a simple regex test `/[a-zA-Z]+/.test($problem[0])` – Arun P Johny Apr 12 '13 at 06:17

3 Answers3

2

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
}
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0
'x+5'.split(/[\W]+/g)

'xyx-2a*yb+5'.split(/[\W]+/g)
Ejaz
  • 8,719
  • 3
  • 34
  • 49
0

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!

A J
  • 2,112
  • 15
  • 24