简体   繁体   English

JavaScript 中的 @Contains 等价物是什么?

[英]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.我正在尝试查看我的 item.data.file(这是我的文件名)是否以任何扩展名结尾,如果是,则执行该行。

In lotus notes, there's @Contains so I would just do that, but does anyone know how do to this in javascript?在 lotus notes 中,有 @Contains 所以我会这样做,但是有人知道如何在 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.我的代码在 if 语句中给了我错误。

Your best bet here would be the Array.indexOf() method:你最好的选择是Array.indexOf()方法:

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.在 JS 中,数组有.include方法来检查数组是否包含参数。 Eg [1,2,3].includes(2) .例如[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 . JS 有一个名为includes方法,它等同于 contains,但由于在这里您试图匹配文件扩展名,我认为您不能单独使用它includes ,您需要在. 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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