JavaScript includes() method


The includes() method in JavaScript is used to determine whether a given string contains a specified substring (search string). It returns a boolean value (true or false) based on whether the substring is found within the string.

Syntax:

string.includes(searchString, position)
  • searchString: The substring you want to search for within the string.
  • position (optional): The position in the string at which to begin the search. If omitted, the default is 0 (the start of the string).

Return Value:

  • It returns true if the searchString is found in the string; otherwise, it returns false.

Example 1: Basic Usage

let phrase = "Hello, world!"; let result = phrase.includes("world"); console.log(result); // true

In this example, the substring "world" is found within the string "Hello, world!", so includes() returns true.

Example 2: Case Sensitivity

The includes() method is case-sensitive. This means that "Hello" and "hello" are treated as different strings.

let text = "Hello, World!"; console.log(text.includes("world")); // false console.log(text.includes("World")); // true

Example 3: Specifying the Starting Position

You can specify the position to start the search using the second parameter. The search begins at the specified index, and it does not search any earlier in the string.

let sentence = "The quick brown fox jumps over the lazy dog."; console.log(sentence.includes("fox", 10)); // true (search starts after "The quick ") console.log(sentence.includes("fox", 20)); // false (search starts after "The quick brown ")

Example 4: Using includes() with Special Characters

The method works with strings that contain special characters, spaces, or punctuation.

let specialString = "Hello, how's it going?"; console.log(specialString.includes("how's")); // true console.log(specialString.includes("going?")); // true console.log(specialString.includes("goodbye")); // false

Example 5: Strings That Do Not Contain the Substring

If the searchString is not found in the original string, the method will return false.

let greeting = "Good morning!"; console.log(greeting.includes("evening")); // false

Example 6: Finding Empty Strings

The includes() method will return true if you search for an empty string, as every string contains an empty substring.

let example = "Hello"; console.log(example.includes("")); // true

Summary:

  • The includes() method checks if a string contains a specific substring and returns true or false.
  • It is case-sensitive and can accept a second argument to specify the starting position for the search.
  • The method works with any character, including special characters and spaces.
  • If you search for an empty string, it will always return true since every string contains an empty substring.