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

Overview

If we want to extract or get a part of a string, we use a string's slice() method.

TypeScript is similar to JavaScript because it is the parent of JavaScript. Therefore, the slice() method is available in JavaScript as well.

For the slice() method, we just need to specify the starting and ending index position for which the extraction should begin and end.

Syntax

Error: Code Block Widget Crashed, Please Contact Support

Parameters

start: This is an integer that 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 substring of the string string is returned.

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.slice(0, 3)
let extract2 = role.slice(9, 12)
let extract3 = hubby.slice(8, 15)
// print the extracted substrings
console.log(extract1)
console.log(extract2)
console.log(extract3)
Extract parts of a string using the slice() method

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 some strings.
  • Lines 9-11: We extract some parts of the strings using the slice() method. Then, we save the results to some variables.
  • Lines 14-16: We log out the extracted strings to the console.

Free Resources