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.
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.
A substring of the string string
is returned.
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)
slice()
method. Then, we save the results to some variables.