Checking for Substring with search() Method
In this approach, the search() method is called on the str string with a regular expression object created from the substring value using the new RegExp(substring). It searches for the first occurrence of the substring within the string. By checking if the result is not equal to -1, we determine if the substring exists in the string. The boolean result is stored in the containsSubstring variable and printed to the console.
Syntax:
string.search(new RegExp)
Example: Here, we are using the above-explained approach.
let str = "Hello there! Welcome to w3wiki"
let substring = "geeks";
let result = str.search(new RegExp(substring)) !== -1;
console.log(result);
Output
true
Explanation:
A regular expression is created using new RegExp(substring)
to match the substring “geeks”. The search()
method is used to find the index of substring
within str
. The boolean result (whether substring
is found in str
) is assigned to result
.
We can check the whether a String Contains a Substring using Loadsh
You can check for substring using Lodash _.strContains() methd, In this approach we can use the lodash _.strContains() method, It will check the presence of he given substring into the given string and return the boolean value.
// Defining lodash contrib variable
let _ = require('lodash-contrib');
let bool = _.strContains("w3wiki", "Geeks");
console.log("The String contains the "
+ "searched String : ", bool);
How to check whether a string contains a substring in JavaScript ?
A substring is a portion of a string. It represents a sequence of characters extracted from a larger string. A substring can be as short as a single character or extend to multiple characters.
There are several approaches to check whether a string contains a substring or not:
Table of Content
- Checking for Substring with includes() Method
- Checking for Substring with test() Method
- Checking for Substring with match() Method
- Checking for Substring with indexOf() Method
- Checking for Substring with search() Method