Open In App

Check an array of strings contains a substring in JavaScript

Improve
Improve
Like Article
Like
Save
Share
Report

The string is the combination of the characters and a substring is the subset of a string. We will be given a substring and a string and we need to check whether the given substring is present in the given string or not.

These are the following ways to do this:

Method 1: 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.

Example: This example shows the implementation of the above-explained approach.

Javascript




const arr = ['Geeks', 'gfg', 'GeeksforGeeks', 'abc'];
const substr = 'eks';
 
const subArr = arr.filter(str => str.includes(substr));
 
console.log(subArr);


Output

[ 'Geeks', 'GeeksforGeeks' ]

Method 2: 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.

Example: This example shows the implementation of the above-explained approach.

Javascript




const arr = ['Geeks', 'gfg', 'GeeksforGeeks', 'abc'];
const substr = 'eks';
 
const subArr = arr.some(str => str.includes(substr));
 
console.log(subArr);


Output

true

Method 3: Using indexOf() method

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

Example: This example shows the implementation of the above-explained approach.

Javascript




const arr = "geeksforgeeks"
const substr = 'eks';
 
const subArr = arr.indexOf(substr);
 
if (subArr) { console.log("true") }
else { console.log("false") }


Output

true

Method 4: 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.

Example: This example shows the implementation of the above-explained approach.

Javascript




// Defining lodash contrib variable
let _ = require('lodash-contrib');
 
let bool = _.strContains("abc", "a");
 
console.log("The String contains the "
    + "searched String : ", bool);


Output:

The String contains the searched String : false


Last Updated : 13 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads