Open In App

TypeScript String endsWith() Method

Last Updated : 19 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The endsWith() method in TypeScript checks if a string ends with a specified substring. It accepts the substring to search for and an optional position parameter to end the search at a specific index, returning a boolean result.

Syntax

string.endsWith(searchString: string, position?: number): boolean;

Parameter

  • searchString: The string you want to see if the original string ends with.
  • position (optional): Here you can pass an index position from where you want to start searching the default is the end of the string.

Return Value: It returns true if the original string ends with searchString otherwise false.

Example 1: Basic Usage

This example demonstrates how to use the endsWith() method to check if a string ends with a specific substring.

JavaScript
const str: string = "Hello, TypeScript!";
const result: boolean = str.endsWith("TypeScript!");
console.log(result);  

Output:

true

Example 2: Validating a File Extension

This example shows how to use the endsWith() method to validate if a file name ends with a specific extension.

JavaScript
const fileName: string = "document.pdf";
const isValid: boolean = fileName.endsWith(".pdf");
console.log(isValid);  // Output: true

Output:

true

Next Article

Similar Reads