简体   繁体   中英

What is the @Contains equivalent in JavaScript?

I'm trying to see if my item.data.file (which is my file name) ends in any of the extensions, if so, then execute the line.

In lotus notes, there's @Contains so I would just do that, but does anyone know how do to this in javascript? I'm not looking for the index, or any boolean i just want to execute the line.

var goodExtensions = ["jpg,", "gif", "bmp", "png"];

if(image.data.file.includes(goodExtensions)
{
   //execute statement
}

My code is giving me errors on my if statement.

Your best bet here would be the Array.indexOf() method:

if (goodExtensions.indexOf(extension) !== -1) {
    // the extension is on the list, do something
}

To find the extension from a filename, something like this should work:

var extension = filename.split(".").pop();

In JS, arrays have the .include method which checks if the array includes the argument. Eg [1,2,3].includes(2) .

 let goodExtensions = ["jpg,", "gif", "bmp", "png"]; let isGoodFileName = fileName => { let extension = (fileName.match(/\\.(.*)$/) || [])[1]; return goodExtensions.includes(extension); } console.log(isGoodFileName('good.gif')); // true console.log(isGoodFileName('bad.txt')); // false

JS has method named includes which is equivalent to contains, but since here you're trying to match file extension i don't think you can do it includes alone, you need to either split on . and test and last splitted element with your good extensions or use regex

In case your willing to see how to do it with regex, you can build a regex with all the good extension dynamically and test against the filename

 let goodExtensions = ["jpg", "gif", "bmp", "png"]; let pattern = `\\\\.${goodExtensions.join('|')}$` let reg = new RegExp(pattern,'i') let isGoodFileName = fileName => { return reg.test(fileName) } console.log(isGoodFileName('good.gif')); // true console.log(isGoodFileName('bad.txt')); // false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM