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.
string.endsWith(substring, [length])
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.This method returns true
if the given substring ends the string. Otherwise, false
is returned.
Let's look at the code below:
export {}// create some stringslet 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 themconsole.log(greeting.endsWith("Edpresso")) // trueconsole.log(proverb.endsWith("the sun shines")) // trueconsole.log(author.endsWith("Chinua")) // falseconsole.log(book.endsWith("fall", 11)) // true
11
. Then we check if it ends with "fall"
.