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

You can find the first index of a substring in a string in JavaScript using the indexOf() or search() methods. Here's how you can use them:

Using indexOf():

index.tsx
let str = 'Hello, World!';
let index = str.indexOf('o');
console.log(index); // Output: 4
90 chars
4 lines

In the above example, the indexOf() method returns the index of the first occurrence of the letter 'o' in the string 'Hello, World!'.

Using search():

index.tsx
let str = 'Hello, World!';
let index = str.search('o');
console.log(index); // Output: 4
89 chars
4 lines

In the above example, the search() method returns the index of the first occurrence of the letter 'o' in the string 'Hello, World!'.

Both methods will return -1 if the given substring is not found in the string.

gistlibby LogSnag