What is the startsWith() method in TypeScript?
Overview
The startsWith() method in TypeScript checks if a string starts with another specified string. If this is true, then a true is returned. Otherwise, false is returned.
Syntax
string.startsWith(anotherString)
Syntax for startsWith() method in TypeScript
Parameter
anotherString: This is the string we want to check to see if string ends with it.
Return value
The startsWith() method returns true if the specified string anotherString starts the input string. Otherwise, false is returned.
Example
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.startsWith("Welcome")) // trueconsole.log(proverb.startsWith("Make hay")) // trueconsole.log(author.startsWith("Achebe")) // falseconsole.log(book.startsWith("fall")) // false
Explanation
Let's see what's happening in the code above:
- Line 1: We export the code as a module to prevent the issues associated with variable name scope.
- Lines 4–7: We create some strings.
- Lines 10–13: We will check if the strings start with the given substrings and print the results to the console.