How to use a for of loop In Javascript
Using a for of loop and indexOf iterates through each string in the array. It checks if the substring exists in each string using the indexOf method. If found (`indexOf` not equal to `-1`), it sets a flag indicating the substring’s presence.
Example: In this example we creates a new array subArr containing strings from arr that contain the substring ‘eks’ using a loop and indexOf.
const arr = ['Geeks', 'gfg', 'w3wiki', 'abc'];
const substr = 'eks';
let subArr = [];
for (let str of arr) {
if (str.indexOf(substr) !== -1) {
subArr.push(str);
}
}
console.log(subArr);
Output
[ 'Geeks', 'w3wiki' ]
Check an array of strings contains a substring in JavaScript
Checking if an array of strings contains a substring in JavaScript involves iterating through each string in the array and examining if the substring exists within any of them. This process ensures efficient detection of the substring’s presence within the array.
These are the following ways to do this:
Table of Content
- Using includes() method and filter() method
- Using includes() method and some() method
- Using indexOf() method
- Using Lodash _.strContains() Method
- Using a for of loop