Title : Check if a String contains a Substring in JavaScript
1. Check if a String contains a Substring with String.includes():
const str1 = "Hello, world!";
const substring1 = "world";
const containsSubstring1 = str1.includes(substring1);
console.log(containsSubstring1); // Output: true
Explanation:
- We use the
includes()
method on the stringstr1
to check if it contains the substring"world"
. - Since "world" is a part of "Hello, world!",
includes()
returnstrue
.
2. Check if String Doesn't contain a Substring in JavaScript:
const str2 = "Hello, world!";
const substring2 = "foo";
const doesNotContainSubstring2 = !str2.includes(substring2);
console.log(doesNotContainSubstring2); // Output: true
Explanation:
- We use the
includes()
method to check if the stringstr2
contains the substring"foo"
. - Since "foo" is not a part of "Hello, world!",
includes()
returnsfalse
. - Using the logical NOT (
!
) operator, we negate the result, which gives ustrue
.
3. Check if a String contains a Substring with String.indexOf():
const str3 = "Hello, world!";
const substring3 = "world";
const containsSubstring3 = str3.indexOf(substring3) !== -1;
console.log(containsSubstring3); // Output: true
Explanation:
- We use the
indexOf()
method on the stringstr3
to check if it contains the substring"world"
. -
indexOf()
returns the index of the substring in the string if found, otherwise-1
. - Since the substring "world" is found in "Hello, world!" at index position 7,
indexOf()
doesn't return-1
, so the condition evaluates totrue
.
4. Check if String Doesn't contain a Substring using indexOf():
const str4 = "Hello, world!";
const substring4 = "foo";
const doesNotContainSubstring4 = str4.indexOf(substring4) === -1;
console.log(doesNotContainSubstring4); // Output: true
Explanation:
- We use the
indexOf()
method to get the index of the substring"foo"
in the stringstr4
. - Since "foo" is not a part of "Hello, world!",
indexOf()
returns-1
. - We check if the returned value is equal to
-1
to determine if the string doesn't contain the substring, which evaluates totrue
.
5. Using includes() and indexOf() with case sensitivity:
const str5 = "Hello, world!";
const substring5 = "WORLD";
const containsSubstringCaseSensitive = str5.includes(substring5);
console.log(containsSubstringCaseSensitive); // Output: false
const containsSubstringIgnoreCase = str5.toLowerCase().includes(substring5.toLowerCase());
console.log(containsSubstringIgnoreCase); // Output: true
Explanation:
- By default, both
includes()
andindexOf()
are case-sensitive. - In the first example,
"WORLD"
is not found in"Hello, world!"
because of the different case, soincludes()
returnsfalse
. - In the second example, we convert both the string and the substring to lowercase before checking, so
"world"
is found in"hello, world!"
, andincludes()
returnstrue
.
Top comments (0)