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 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.startsWith("Welcome")) // true
console.log(proverb.startsWith("Make hay")) // true
console.log(author.startsWith("Achebe")) // false
console.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.

Free Resources