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:
Table of Content
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.
const arr = [ 'Geeks' , 'gfg' , 'GeeksforGeeks' , 'abc' ];
const substr = 'eks' ;
const subArr = arr.filter(str => str.includes(substr)); console.log(subArr); |
[ '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.
const arr = [ 'Geeks' , 'gfg' , 'GeeksforGeeks' , 'abc' ];
const substr = 'eks' ;
const subArr = arr.some(str => str.includes(substr)); console.log(subArr); |
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.
const arr = "geeksforgeeks"
const substr = 'eks' ;
const subArr = arr.indexOf(substr); if (subArr) { console.log( "true" ) }
else { console.log( "false" ) }
|
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.
// 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