The String.substr() method in TypeScript is an inbuilt function used to extract a portion of a string, starting at a specified index and extending for a given number of characters.
Syntax:
string.substr(start[, length])Parameter: This method accepts two parameters as mentioned above and described below.:
- start - This parameter is the location at which to start extracting characters.
- length - This parameter is the number of characters to extract.
Return Value: This method returns the new sub-string.
The below examples illustrate the String substr() method in TypeScript.
Example 1: Extracting a Substring from the Beginning
In this example we use substr() to extract a substring from str, starting at index 0 and spanning 5 characters.
let str: string = "GeeksforGeeks";
let result: string = str.substr(0, 5);
console.log(result); // Output: Geeks
Output:
Geeks
Example 2: Extracting a Substring from the Middle
In this example we use substr() to extract a substring from str, starting at index 5 and spanning 3 characters.
let str: string = "GeeksforGeeks";
let result: string = str.substr(5, 3);
console.log(result); // Output: for
Output:
forExample 3: Extracting to the End of the String
In this example we use substr() to extract a substring from str, starting at index 8 and continuing to the end.
let str: string = "GeeksforGeeks";
let result: string = str.substr(8);
console.log(result); // Output: Geeks
Output:
GeeksExample 4: Extracting with Negative Start Index
In this example we use substr() to extract a substring from str, starting 5 characters from the end and spanning 4 characters.
let str: string = "GeeksforGeeks";
let result: string = str.substr(-5, 4);
console.log(result); // Output: Geek
Output:
Geek