Search code examples
javascriptjquerystringsearchletter

Javascript / jQuery search for letter in string


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.


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
    }