Looking to get a head start on your next software interview? Pickup a copy of the best book to prepare: Cracking The Coding Interview!
To use `indexOf()` in TypeScript, first declare a string variable and assign it a value:
let myString: string = "Hello, world!";
Then, call the `indexOf()` method on the string variable and pass in the character or substring you want to find:
let index: number = myString.indexOf("world");
This will return the index of the first occurrence of the substring “world” within the string “Hello, world!”. If the substring is not found, `indexOf()` will return -1.
It’s important to note that `indexOf()` is case-sensitive, so if you’re searching for a substring with a specific case, make sure to match the case exactly.
In addition to searching for substrings, `indexOf()` can also be used to search for individual characters within a string. For example:
let index: number = myString.indexOf("o");
This will return the index of the first occurrence of the character “o” within the string “Hello, world!”.
Overall, `indexOf()` is a powerful method for searching within strings in TypeScript, and can be used in a variety of different scenarios.