1

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?

2
  • 1
    Type "javascript index of" into Google, and follow what its auto-correct suggests ...? Commented Dec 16, 2017 at 9:50
  • the each word make the difference here Commented Dec 16, 2017 at 9:52

5 Answers 5

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;
})
Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

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)
  }
});

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.