This practical article walks you through 4 different ways to check whether a given string contains a substring or not. Without any further ado (like talking about the history of Javascript or explaining what a string is), let’s get started.
Using regular expression
Regular expressions, or regex for short, is a powerful tool for checking if a string contains a substring in Javascript. You can flexibly choose between case-sensitive (default) or case-insensitive. Let’s take a look at the following example for more clarity:
// define a function for reusability
const check = (str, subStr, caseSensitive = false) => {
if (caseSensitive) {
return new RegExp(subStr).test(str);
}
return new RegExp(subStr, 'i').test(str);
}
// try the function
console.log(check('abc def ghi', 'abc')); // true
console.log(check('abc def ghi', 'ABC')); // false
console.log(check('abc def ghi', 'ABC', false)); // true
Compared to the next 2 solutions, this one is a bit longer, but it is the only solution that allows us to check with case insensitive.
Using the includes() method
The syntax for using the includes() method is as follows:
string.includes(substring);
The includes() method returns true if a string contains another string. Otherwise, it returns false. It’s important to note that this method is case-sensitive.
Example:
const str = 'Hello World';
const subStr1 = 'World';
const subStr2 = 'Worlds';
console.log(str.includes(subStr1)); // true
console.log(str.includes(subStr2)); // false
Using the indexOf() method
The syntax:
string.indexOf(substring)
The indexOf() method will return the position of the first occurrence of the substring in the string or -1 if the substring is not found. Similar to the includes() method, the indexOf() method is also case-sensitive.
If you are looking to find the position of a substring within a string, the indexOf() method is a great choice as well.
Example:
const str = "Sling Academy";
const subStr1 = "Academy";
const subStr2 = "Slug";
console.log(str.indexOf(subStr1) !== -1); // true
console.log(str.indexOf(subStr2) !== -1); // false
Using a for loop
We can do lots of things with the classic for loop. The example below shows you how to use it to check if a string contains a substring or not:
const check = (str, subStr) => {
for (let i = 0; i < str.length; i++) {
if (str[i] === subStr[0]) {
for (let j = 1; j < subStr.length; j++) {
if (str[i + j] !== subStr[j]) {
break;
}
if (j === subStr.length - 1) {
return true;
}
}
}
}
return false;
};
console.log(check('hello', 'll')); // true
console.log(check('hello', 'oo')); // false
Although it also gives the correct answer, this approach is unnecessarily verbose. However, it is still useful for your reference purposes.