skip to Main Content

I have a client software program and in it I have a variable, can be used as a string, split, etc, which I want to use within an if statement.

So it may be A|B, in which case I want to run if(A|B)

It may be A|B|C, in which case I want to run if(A|B|C) and so on

I can’t use eval as

  1. it’s a bad thing, and
  2. their software blocks it

Any help appreciated.

I’ve tried splitting, rebuilding into a string, passing via another function, but it won’t play like I want it to.

Is there an easy solution to do this? Without using multiple if, else, or case statements ?

2

Answers


  1. What do you mean "run if (A|B)"

    The simplest is comparing using quotes, assuming you do not mean A OR B when you write A|B

    let str = "A|B"
    
    if (str === "A|B") console.log("It's A|B")
    else if (str === "A|B|C") console.log("It's A|B|C")
    
    // Alternative using RegExp - I escape the pipe symbol
    
    console.log(/^A|B$/.test(str))
    
    console.log(/^A|B|C$/.test(str))
    Login or Signup to reply.
  2. You can archiev this via Array some along with Arra include method like below :

    var yourString = 'A|B|C';
    
    if(yourString.split('|').some(item => ['A','B','C'].includes(item))){
      console.log('String include A or B or C'); // logs contains A or B or C
    }
    
    
    var yourString1 = 'D|E';
    
    if(!yourString1.split('|').some(item => ['A','B','C'].includes(item))){
      console.log('String does not include A or B or C'); // logs does not contains A or B or C 
     }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search