user9366125
user9366125

Reputation:

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.

The above returns meat when it should match fe- and return cheese

Upvotes: 1

Views: 64

Answers (1)

tymeJV
tymeJV

Reputation: 104775

You can use Array.some. It will iterate over an array and return true if any of the iterations return 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.

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.

Upvotes: 6

Related Questions