简体   繁体   English

JavaScript部分匹配数组中的字符串

[英]JavaScript partially match string inside an array

const arr = ['be-', 'fe-', 'automated'];

const str = 'fe-cheese';
const oi = arr.includes(str) ? 'cheese' : 'meat';

console.log(oi);

I have an array of partial matches and I want to check to see if the string contains any of the partials in the arr . 我有一个部分匹配数组,我想检查字符串是否包含arr中的任何部分。

The above returns meat when it should match fe- and return cheese 上面提到的应该与fe-cheese搭配时返回的meat

You can use Array.some . 您可以使用Array.some It will iterate over an array and return true if any of the iterations return true. 它将迭代一个数组,如果任何迭代返回true,则返回true。 Note: This has the added benefit of short-circuit execution, meaning that once it reaches the first iteration that returns true, it does not continue the rest of the iterations, as they are unnecessary. 注意:这具有短路执行的附加好处,这意味着一旦到达返回true的第一个迭代,它就不会继续其余的迭代,因为它们是不必要的。

 const arr = ['be-', 'fe-', 'automated']; const str = 'fe-cheese'; const oi = arr.some(a => str.indexOf(a) > -1) ? 'cheese' : 'meat'; console.log(oi); 

Verify that at least one of the elements is present (indexOf) in the provided string. 验证提供的字符串中是否存在至少一个元素(indexOf)。

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

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