Checking for Substring with slice() Method
In this method, we’ll use the slice() method to extract substrings from the main string and compare them with the search value. This method iterates through the main string, extracts a substring of the same length as the search value at each position, and checks for equality. If a match is found, it returns true.
Note: You need to install lodash-contrib package to run this code.
Example: This example demonstrates using the slice() method to check for a substring in a string.
function containsSubstring(mainString, searchValue) {
let searchLength = searchValue.length;
let mainLength = mainString.length;
for (let i = 0; i <= mainLength - searchLength; i++) {
if (mainString.slice(i, i + searchLength) === searchValue) {
return true;
}
}
return false;
}
let str = "Hello there! Welcome to w3wiki";
let substring = "geeks";
let result = containsSubstring(str, substring);
console.log(result);
Output
true
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