Search code examples
javascriptindexof

indexOf - search value in a string, if not, do something


I have a formula:

Total_ID = id1,id2,id3,...,id10

If myid included in Array “total_ID”, do AAA;

I use:

if (( total_ID.split(",").indexOf(myid.toString()) && (myid !=””))
{AAA}

How can I change my above formula for the following condition?

If myid is not included in Total_ID, do AAA.


Solution

  • You can check whether indexOf() returns -1 or not.

    As per MDN:

    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.

    Total_ID = 'id1,id2,id3,id10';
    myid = 'id4';
    if (Total_ID.split(",").indexOf(myid) == -1){
      console.log('not found');
    }

    Alternatively, you can use Array.includes() which simplifies it:

    Total_ID = 'id1,id2,id3,id10';
    myid = 'id4';
    if (!Total_ID.split(",").includes(myid)){
      console.log('not found');
    }