Code Logo

Check Substring with includes()

Published at25 Jul 2026
JavaScript String Handling Easy 0 views
Like0

Write a JavaScript function that takes two strings and returns true if the first string contains the second substring using the includes() method. String.includes() performs a case-sensitive search and returns a boolean.

String.prototype.includes() is a JavaScript method introduced in ES6 that determines whether one string can be found within another string. It returns true if the search string is found anywhere in the string, and false otherwise. Unlike indexOf() which returns the position or -1, includes() is more readable when you only need a yes/no answer.

The includes() method is case-sensitive and accepts an optional second parameter for the starting position. It is simpler and more modern than using indexOf() !== -1. The method is widely supported in all modern JavaScript environments including Node.js and all major browsers.

Time complexity is O(n) where n is the string length. The method performs a linear search through the string. Space complexity is O(1). The method returns a boolean primitive, not an object wrapper.

Edge cases include empty search string (returns true for any string), case sensitivity, search string longer than the target string (returns false), and special characters (works correctly with any Unicode characters).

Example Input & Output

Example 1
Input
"hello world","world"
Output
true
Explanation

hello world contains world

Example 2
Input
"test","test"
Output
true
Explanation

Exact match

Example 3
Input
"hello world","xyz"
Output
false
Explanation

Does not contain xyz

Example 4
Input
"abc",""
Output
true
Explanation

Empty substring always found

Example 5
Input
"javascript","Script"
Output
false
Explanation

Case-sensitive

Algorithm Flow

Recommendation Algorithm Flow for Check Substring with includes()
Recommendation Algorithm Flow for Check Substring with includes()

Solution Approach

function solution(str, search) {
  return str.includes(search);
}

Best Answers

javascript - Approach 1
function solution(str, search) {
  return str.includes(search);
}