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

We can use the indexOf() method to find the first occurrence of a character in a string in JavaScript.

Here's an example code snippet that demonstrates how to use the indexOf() method:

index.tsx
const str = "Hello World";
const char = "o";

const index = str.indexOf(char);

console.log(index); // Output: 4
113 chars
7 lines

In the example above, we have a string variable str with the value "Hello World". We also have a character variable char with the value "o". We then use the indexOf() method to find the first occurrence of the character "o" in the string str. The method returns the index of the first occurrence, which is 4.

Note that if the character is not found in the string, the indexOf() method returns -1.

gistlibby LogSnag