What is the string.endsWith() method in TypeScript?

Overview

In TypeScript, we can check what a string ends with using the endsWith() method. TypeScript is similar to JavaScript in all ramifications. It is the superset of JavaScript.

Syntax

string.endsWith(substring, [length])
Syntax for endsWith() method in TypeScript

Parameters

  • substring: This is the string we want to check to see if string ends with it.
  • length: This is the length of the string we want to check. By default, it is the length of the string, string.length. We use it to specify the length of the string when finding the substring that ends it. It is an optional parameter.

Return value

This method returns true if the given substring ends the string. Otherwise, false is returned.

Code example

Let's look at the code below:

export {}
// create some strings
let greeting:string = "Welcome to Edpresso"
let proverb:string = "Make hay while the sun shines"
let author:string = "Chinua Achebe"
let book:string = "Things fall apart"
// check if some substrings end them
console.log(greeting.endsWith("Edpresso")) // true
console.log(proverb.endsWith("the sun shines")) // true
console.log(author.endsWith("Chinua")) // false
console.log(book.endsWith("fall", 11)) // true

Explanation

  • Line 1: We export our code as a module to prevent variable names issues.
  • Lines 4 to 7: We create some strings.
  • Lines 10 to 12: We check if the strings end with some substrings.
  • Line 13: We specify the length of the string we want to check if it ends with a particular string, 11. Then we check if it ends with "fall".

Free Resources