0

Here are two if conditions with different checks:

CASE 1:

if(plan_name.indexOf("T1")>=0 && plan_name.indexOf("FLEX")>=0 && plan_name.indexOf("Non-VAE")>=0) {
    //do something
}

followed by (in same code/program)

CASE 2:

if(plan_name.indexOf("T1")>=0 && plan_name.indexOf("Non-FLEX")>=0 && plan_name.indexOf("Non-VAE")>=0){
    //do something
}

Here is the input to which above conditions get applied:

plan name = iOS 7.7 - RC - T1 - Non-FLEX, Non-VAE

In my code everytime the first if condition in CASE 1 is becoming valid because indexOf() is detecting the substring and not the actual specific string that I want the code to detect(that is CASE 2 should be valid). How to make such specific string match in JS?

8
  • 1
    if is not a loop :) Commented Oct 6, 2016 at 19:19
  • My bad, fixed ...changed to conditions Commented Oct 6, 2016 at 19:20
  • So you need to rip it apart and compare the pieces Commented Oct 6, 2016 at 19:21
  • 1
    And how do you suppose that would work? The string FLEX is part of Non-FLEX and will always match, if you don't want to match, you'll need to add characters, even if those characters are spaces (hint). Commented Oct 6, 2016 at 19:24
  • 1
    @charlietfl - or just indexOf(" FLEX") Commented Oct 6, 2016 at 19:26

3 Answers 3

1

One solution is split it apart and see if the string matches in the array

var str = "iOS 7.7 - RC - T1 - Non-FLEX, Non-VAE";
var parts = str.split(/[\s,]/g);
console.log("FLEX", parts.indexOf("FLEX")!==-1);
console.log("Non-FLEX", parts.indexOf("Non-FLEX")!==-1);
Sign up to request clarification or add additional context in comments.

Comments

0

your check should be like this

plan_name.indexOf("T1")>=-1

not this

plan_name.indexOf("T1")>=0 

Comments

0

One option is to reorder your execution flow:

if(plan_name.indexOf("T1")>=0 && 
      plan_name.indexOf("Non-FLEX")>=0 &&
      plan_name.indexOf("Non-VAE")>=0){
    ...
} else if(plan_name.indexOf("T1")>=0 && 
      plan_name.indexOf("FLEX")>=0 &&
      plan_name.indexOf("Non-VAE")>=0) {
   ...
}

As the first condition is stricter than the second, the second one will only be checked if the first one is not true.

However, this only works if there are no more options, because if you have to look also for 'VAE' and 'Non-VAE', then maybe you should "tokenize" the string: as it seems the tokens are separated by spaces, you could split it and then look in the resulting array for each token you need.

A third option, still assuming that the tokens are separated by spaces is adding a space to your matcher: instead of 'FLEX' look for ' FLEX' and ' Non-Flex'

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.