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

Overview

TypeScript is the parent of JavaScript, and they both have similar methods. In fact, anywhere JavaScript runs, TypeScript runs as well. With the substring() method, we can extract a certain part of a string by specifying where to start and end the extraction.

Syntax

string.substring(start, end)
The syntax for the substring() method in TypeScript

Parameters

start: This is an integer. It represents the index position in the string from where we want to start the extraction.

end: This is also an integer that represents the end position where the extraction should stop.

Return value

A string is returned, which contains the extracted characters.

Example

export {}
// create some strings
let name:string = "Theodore"
let role:string = "Software Developer"
let hubby:string = "Coding, Writing, Reading"
// extract parts of the strings
let extract1 = name.substring(0, 3)
let extract2 = role.substring(9, 12)
let extract3 = hubby.substring(8, 15)
// print the extracted substrings
console.log(extract1)
console.log(extract2)
console.log(extract3)

Explanation

  • Line 1: We export our code as a module. This is to prevent any problem related to variable scoping.
  • Lines 4–6: We create three strings.
  • Lines 9–11: We extract the substrings by setting the start and end index values. Then we save the results to some variables.
  • Lines 14–16: Finally, we print the extracted substrings to the console.

Free Resources