0

I have a complex expression consisting of LHS, operators, RHS. In the expression, I need to place an input box in place of each RHS and append the value inside it.

So, I thought of finding the position of all the operators in the expression, and place an input box next to it. Her's an Example:

I have a string var a = "(temp >= 10) && (humid >= 20) " wherein, I need to find each position(index) of >= in the string expression.

I tried comparing single characters, but that is not helping me. How do I need to do this using Javascript or Jquery?

Darshan theerth
  • 516
  • 1
  • 13
  • 34

5 Answers5

3

to get a single index of a substring so you have to use the famous indexOf method.

to get all indices you may use this trick

var indices = [];
var str = 'var expression = "(temp >= 10) && (humid >= 20)"'

// using a regex with the global flag
str.replace(/>=/g, function(q, index) {
  indices.push(index)
  return q;
})
amd
  • 20,637
  • 6
  • 49
  • 67
1

Try the following:

var expression = "(temp >= 10) && (humid >= 20)";
expression = expression.split('');
expression.forEach(function(item, i){
  if(item === '>'){
    console.log('position of >: ' + i)
  }
  else if(item === '='){
    console.log('position of =: ' + i)
  }
});
Mamun
  • 66,969
  • 9
  • 47
  • 59
1

What you need is a regex to do a global search in the string. Like var regex = />=/gi Check the already existing answer given here

Sandip Ghosh
  • 719
  • 7
  • 13
1

You could use indexOf and then use a loop to check the return value.

From the docs

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

var a = 'var a = "(temp >= 10) && (humid >= 20) "';
var positions = [];
var position = -1;
while ((position = a.indexOf(">=", position + 1)) !== -1) {
    positions.push(position);
}
console.log(positions);
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
0

you may refer to indexOf

indexOf will return the first index where the match is true, try:

console.log(expression.indexOf('>='));

this will print the index of the first '>=' occurrence. indexOf can take a second argument which specifies the starting index of the search, expression.indexOf('>=', 7); (where 7 is the index of the first occurrence) will get the second index.

OSAMAH
  • 139
  • 3