Member-only story
How to Check Whether a String Contains a Substring in JavaScript
JavaScript provides a number of ways to check whether a string contains a substring. In this blog post, we will discuss three of the most common methods:
- The
includes()
method - The
indexOf()
method
The includes()
Method
The includes()
method was introduced in ES6, and it is the most concise and efficient way to check whether a string contains a substring.
The includes()
method takes two arguments:
- The first argument is the substring you want to check for
- The second argument is the optional index at which you want to start the search.
If the substring is found, the includes()
method returns true
; otherwise, it returns false
.
For example, the following code checks whether the string "hello world"
contains the substring "world"
:
Code snippet
const str = "hello world";
const substring = "world";
const result = str.includes(substring);
console.log(result); // true
The indexOf()
Method
The indexOf()
method takes two arguments:
- The first argument is the substring you want to check for
- The second argument is the optional index at which you want to start the search.
If the substring is found, the indexOf()
method returns the index of the first occurrence of the substring within the string; otherwise, it returns -1
.
For example, the following code checks whether the string "hello world"
contains the substring "world"
:
const str = "hello world";
const substring = "world";
const index = str.indexOf(substring);
console.log(index); // 6
Conclusion
In this blog post, you learned how to check whether a string contains a substring using includes()
anf indexOf()
method.
I hope this blog post has been helpful. If you have any questions, please feel free to leave a comment below.