The indexOf() method in TypeScript is an inbuilt function used to find the index of the first occurrence of a specified value within a calling string. If the value is not found, it returns -1.
Syntax
string.indexOf(searchValue[, fromIndex]) Parameter: This method accepts two parameters as mentioned above and described below.
- searchValue: This parameter is a string representing the value to search for.
- fromIndex: This parameter is a location within the calling string to start the search from.
Return Value: This method returns the index of the found occurrence, otherwise -1 if not found.
The below example illustrates the String indexOf() method in TypeScriptJS:
Example 1: Finding a Substring
In this example we finds the position of "world" in the string str using indexOf, which returns 21 because world starts at the 21st character (0-based index).
let str: string = "Hello, welcome to the world of TypeScript.";
let index: number = str.indexOf("world");
console.log(index); // Output: 21
Output:
21Example 2: Substring Not Found
In this example we searches for JavaScript in str using indexOf, returning -1 because JavaScript is not found within the string.
let str: string = "Hello, welcome to the world of TypeScript.";
let index: number = str.indexOf("JavaScript");
console.log(index); // Output: -1
Output:
-1