find the first index of a character in a string in typescript

To find the first index of a character in a string in TypeScript, you can use the indexOf method. This method returns the index of the first occurrence of a specified character or substring in a string. Here is an example:

index.ts
let myString = "Hello world";
let charIndex = myString.indexOf("o");
console.log(charIndex); // Output: 4
106 chars
4 lines

In the above example, we first declare a string variable named myString with the value "Hello world". Then, we use the indexOf method to find the first occurrence of the character "o" in this string. The method returns the index of the first occurrence, which is 4. Finally, we log this index to the console.

Note that the indexOf method is case-sensitive. If you want to perform a case-insensitive search, you can use the toLowerCase method on the string before calling indexOf, like this:

index.ts
let myString = "Hello world";
let charIndex = myString.toLowerCase().indexOf("o");
console.log(charIndex); // Output: 4
120 chars
4 lines

In this example, we convert the string to lowercase before calling indexOf, so that we can find both uppercase and lowercase occurrences of the character "o".

related categories

gistlibby LogSnag