Tsardines
Tsardines

Reputation: 943

Using a logical operator within .includes()--getting an error

I have some code that appends a file extension icon next to a specific document---i.e. all of the .pdf files have a PDF icon right next to it.

Some documents end in doc and DOCX, and so I tried to implement .includes('doc' || 'DOCX'), but I'm receiving an error and DOCX ends up not loading. As such I've just done .includes('ext name')) { return...etc for every variation, but it's cumbersome and I want to see if they can be shortened.

I tried to research if logical operators were allowed with .includes(), but nothing came up. Is this why I'm getting an error, or is there another reason?

Here's my JS:

function docType(fileName) {
    let docImg = "<img src='https://url/Current.ashx/docx.gif'  />"
    let msgImg = "<img src='https://url/Current.ashx/msg.gif'   />"

    let docStr = fileName.split(".");
      for (var i = 0; i < docStr.length; i++) {
       if (docStr[i].includes('doc' || 'DOCX')) { return docStr[i] = docImg;  } 
  else if (docStr[i].includes('msg')) { return docStr[i] = msgImg;  } 

      }
  } // docType

Upvotes: 0

Views: 29

Answers (2)

Bergi
Bergi

Reputation: 664764

includes checks against the value that is passed as an argument. It does not evaluate any user code during the check. You will need to use

if (docStr[i].includes('doc') || docStr[i].includes('doc'))

Upvotes: 1

charlietfl
charlietfl

Reputation: 171679

Other than multiple includes or a regex you can also use Array#some()

Try

if(['doc','DOCX'].some(s = > docStr[i].includes(s)))

Upvotes: 1

Related Questions