The substring() is an inbuilt function in TypeScript that returns the subset of a String object. It takes two parameters: indexA (starting index) and optional indexB (ending index, non-inclusive). It returns the portion of the string between these indices.
Syntax
string.substring(indexA, [indexB]) Parameter: This method accepts two parameters as mentioned above and described below:
- indexA : This parameter is the integer between 0 and one less than the length of the string.
- indexB : This parameter is the integer between 0 and the length of the string.
Return Value: This method returns the subset of a String object.
Below example illustrate the String substring() method in TypeScript.
Example 1: Basic Usage
In this example we extracts a substring from str, starting at index 0 and ending at index 5.
// Original strings
let str: string = "Geeksforgeeks - Best Platform";
// Use of String substring() Method
let newstr: string = str.substring(0, 5);
console.log(newstr);
Output:
GeeksExample 2: Extracting Substrings with Different Indices
In this example, we demonstrate the use of substring() with different indices to extract various parts of the string.
// Original strings
let str: string = "Geeksforgeeks - Best Platform";
// Use of String substring() Method
let newstr: string = str.substring(0, 5);
console.log(newstr); // Output: "Geeks"
newstr = str.substring(-2, 5);
console.log(newstr); // Output: "Geeks"
newstr = str.substring(12, 22);
console.log(newstr); // Output: "ks - Best "
newstr = str.substring(0, 1);
console.log(newstr); // Output: "G"
Output:
Geeks
Geeks
s - Best P
G