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
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 stringslet name:string = "Theodore"let role:string = "Software Developer"let hubby:string = "Coding, Writing, Reading"// extract parts of the stringslet extract1 = name.slice(0, 3)let extract2 = role.slice(9, 12)let extract3 = hubby.slice(8, 15)// print the extracted substringsconsole.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 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.