简体   繁体   中英

How can one check if an array contains a substring?

Is it possible to check if an array of strings contains a substring? I know how to find whether an array has a complete string match (using $.inArray, arr.includes, arr.indexOf etc...), but these don't match a substring to an array of strings (at least for me).

If I have a <select multiple> element with the following options:

positive (selected)
positron (selected)
negative
negatron

How do can I boolean whether my multiple options array includes the substring pos , to indicate that both positve and positron were in the selections?

I'd like to be able to present my user with some additional questions to answer based on whether certain selections are made, but I don't want to write a bunch of if/then statements to cover the various strings.

You can use indexOf to check if an array element contain substring

 var testData = ['positive', 'negative'] testData.forEach(function(item) { if (item.indexOf('pos') !== -1) { console.log('Hava data') } }) 

The Array.prototype has very useful .filter function for your purpose.

 const arr = ['positive', 'positron', 'negative', 'negatron']; function findMatches() { let searchVal = document.getElementById('test').value; let res = arr.filter(el => el.indexOf(searchVal) > -1); document.getElementById('result').innerHTML = res.join(', '); } 
 <input type="text" id="test" /> <button type="button" onclick="findMatches()">Find</button> <br /> Array: ['positive', 'positron', 'negative', 'negatron']<br /> <span id="result"></span> 

And then apply your extended logic to the filtered array.

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