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.

JavaScript
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

Similar Reads

Using includes() method and filter() method

First, we will create an array of strings, and then use includes() and filter() methods to check whether the array elements contain a sub-string or not....

Using includes() method and some() method

First, we will create an array of strings, and then use includes() and some() methods to check whether the array elements contain a sub-string or not....

Using indexOf() method

In this approach, we are using indexOf() method that returns the index of the given value in the given collection....

Using Lodash _.strContains() Method

In this example, we are using the Lodash _.strContains() method that return the boolean value true if the given value is present in the given string else it returns false....

Using a for of loop

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....