Check an array of strings contains a substring in JavaScript
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:
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' ]
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);
|
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" ) }
|
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
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
Share your thoughts in the comments
Please Login to comment...