Open In App

TypeScript String endsWith() Method

The endsWith() function, in TypeScript as well as JavaScript, is a built-in method that checks if a particular string ends with another specific string or not.

Syntax

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

Parameter:

Return Value:

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



Example 1: To demonstrate the usage of the endWith() method.




const str: string = "Hello, world!";
console.log(str.endsWith("world!"));

Output:



true

Example 2: To demonstrate validating a file extension using endsWith() method.




function fileExtension(
    fileName: string, allowedExtension: string):
        boolean {
    return fileName.endsWith(allowedExtension);
}
 
const isValidImage: boolean =
    fileExtension("myphoto.jpg", ".jpg");
 
console.log(isValidImage);

Output:

true
Article Tags :