How to Check Whether a String Contains a Substring in JavaScript
2 min readJul 11, 2023
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