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:
- 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: To demonstrate the usage of the endWith() method.
Javascript
const str: string = "Hello, world!" ; console.log(str.endsWith( "world!" )); |
Output:
true
Example 2: To demonstrate validating a file extension using endsWith() method.
Javascript
function fileExtension( fileName: string, allowedExtension: string): boolean { return fileName.endsWith(allowedExtension); } const isValidImage: boolean = fileExtension( "myphoto.jpg" , ".jpg" ); console.log(isValidImage); |
Output:
true
Contact Us