Member-only story
In JavaScript, you can detect if a string is contained within another string using the includes()
method or the indexOf()
method.
Here’s an example of using the includes()
method:
const str1 = "hello world";
const str2 = "world";
if (str1.includes(str2)) {
console.log(`${str2} is found in ${str1}`);
} else {
console.log(`${str2} is not found in ${str1}`);
}
In this example, the includes()
method checks whether str2
is found in str1
. If it is found, it returns true
, otherwise it returns false
.
Here’s an example of using the indexOf()
method:
const str1 = "hello world";
const str2 = "world";
if (str1.indexOf(str2) !== -1) {
console.log(`${str2} is found in ${str1}`);
} else {
console.log(`${str2} is not found in ${str1}`);
}
In this example, the indexOf()
method checks whether str2
is found in str1
. If it is found, it returns the index of the first occurrence of str2
in str1
. If it is not found, it returns -1
. We use the !==
operator to check if the returned value is not -1
, which means str2
is found in str1
.
Both includes()
and indexOf()
are case-sensitive. If you want to perform a case-insensitive search, you can convert both strings to lowercase or uppercase before performing the search. For example:
const str1 = "Hello World";
const str2 = "WORLD";
if (str1.toLowerCase().includes(str2.toLowerCase())) {
console.log(`${str2} is found in ${str1}`);
} else {
console.log(`${str2} is not found in ${str1}`);
}
In this example, we convert both str1
and str2
to lowercase using the toLowerCase()
method before performing the search.