0

I want to get a True or False value by putting a value in the sTest_Val_1 ("30") variable.

So we try to split and separate variables and operators.

At first I used the following source code.

However, this source code has caused problems because it is also splitting "_" from sTest_Val_1.

I could not split properly because of special characters in variables. So I could not put a value of "30" into the variable.

 var expression = "sTest_Val_1 < 50";  //or "sTest_Val_1<50"
 var copy = expression; //"sTest_Val_1 < 50"

 expression = expression.replace(/[0-9a-zA-Z]+/g, "#");  //"#_#_# < #"
 var numbers = copy.split(/[^0-9a-zA-Z\.]+/); //[sTest,Val,1,50]
 var operators = expression.split("#").filter(function (n) { return n }); //[_,_, < ]
 var result = [];
 var sRst = "";

 result.push(numbers[i]);
 sRst += numbers[i];
 if (i < operators.length) {
    result.push(operators[i]);
    sRst += operators[i];

 console.log(sRst);  
 return eval(sRst);  // I want True, False

The value of sTest_Val_1 is defined in another page. (i get this value to javascript object when first page loaded.)

string sTest_Val_1 = "30";
string sTest_Val_2 = "30";
string sTimeVal_1 = "65380";
// ....

"sTest_Val_1" This value can only contain alphabetic characters in the first character.

However, the length of the characters is random, and the special characters in the characters are also random. (<,>, +, -, and = are not included.)

My English is not good enough. Please understand.

cherryJang
  • 75
  • 5

2 Answers2

0

You can use RegEx to find the position of the operator, without knowing the exact operator. /<|>|\+|\-|=|&&/ will match <, >, +, = or &&

var expression = "sTest_Val_1 < 50";  //or "sTest_Val_1<50"
var regResult = /<|>|\+|\-|=|&&/.exec(expression); //match <, >, +, = or &&
if(!regResult.length){ //regResult is an array containing the operators found
   // handle no operator found
}
var opIdx = regResult.index; //the index of the first found operator
var op = regResult[0];
var variable = expression.substring(0, opIdx).trim(); //split until operator and trim whitespaces
var value = expression.substring(opIdx + op.length, expression.length).trim(); //split after operator and trim whitespaces

Note: if you are expecting multiple operators in the expression, you should probably loop through regResult and do some modifications to the substring arguments.

Also, using eval is a bad ideea, I would recommend you to do a switch on the operator and check the condition properly for returning the result of the operation.

Alexandru Severin
  • 6,021
  • 11
  • 48
  • 71
0

You can split by operator (with keeping the operator) with capturing group.

expression = "sTest_Val_1 < 50"
expression.split(/(<|>|\+|\-|=|&&)/)

will result in ["sTest_Val_1 ", "<", " 50"]

Fallenhero
  • 1,563
  • 1
  • 8
  • 17