TypeScript String includes()

In this chapter, we will explore the includes() method in TypeScript. This method is a built-in function that helps in determining whether one string contains another substring. Understanding how to use includes() is useful for checking the presence of substrings within strings.

Table of Contents

  1. Definition
  2. Syntax
  3. Examples
  4. Conclusion

1. Definition

The includes() method determines whether one string contains another substring. It returns true if the substring is found within the string, and false otherwise.

2. Syntax

string.includes(searchString, position?); 

Parameters

  • searchString: The substring to search for within the string.
  • position (optional): The position within the string at which to begin searching for searchString. Defaults to 0.

Return Value

The method returns a boolean value: true if the searchString is found within the string, otherwise false.

3. Examples

Let’s look at some examples to understand how includes() works in TypeScript.

Example 1: Basic Usage

In this example, we check if a string contains a specific substring.

let str: string = "Hello, TypeScript!"; console.log(str.includes("TypeScript")); // Output: true console.log(str.includes("JavaScript")); // Output: false 

Example 2: Using includes() with Position

In this example, we use the position parameter to start the search from a specific index.

let str: string = "Hello, TypeScript!"; console.log(str.includes("Type", 7)); // Output: true console.log(str.includes("Hello", 1)); // Output: false 

Example 3: Case Sensitivity

The includes() method is case-sensitive. In this example, we see how case sensitivity affects the result.

let str: string = "Hello, TypeScript!"; console.log(str.includes("typescript")); // Output: false console.log(str.includes("TypeScript")); // Output: true 

Example 4: Searching for an Empty String

In this example, we search for an empty string within another string.

let str: string = "Hello, TypeScript!"; console.log(str.includes("")); // Output: true 

4. Conclusion

In this chapter, we explored the includes() method in TypeScript, which is used to determine whether a string contains another substring. We covered its definition, syntax, parameters, return value, and provided several examples to demonstrate its usage. Understanding how to use includes() effectively can help in various string manipulation tasks in TypeScript, especially when checking for the presence of substrings within strings.

Leave a Comment

Scroll to Top