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.ts106 chars4 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.ts120 chars4 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".
gistlibby LogSnag