Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

typescript
slice
string
communitycreator

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

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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

string.slice(start, end)
The syntax for the slice() method of a string in TypeScript

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.

RELATED TAGS

typescript
slice
string
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring