Javascript String Indexof Method

Javascript String Indexof Method

As the name says, this method returns the index of the first occurrence of some specified string in some string javascript. It’s like we are finding the first occurrence of some string inside a string.

Javascript String Indexof Method

Remember that we have to give the string, whose first occurrence are we searching for. This is like we call the indexOf method, and just say that – hey indexOf, take this string, and return the first occurrence index of the string in the given string. So, simply the index of the first occurrence of some string will be returned.

Remember that a character is also a single-length string here.

Always, the string index starts from zero, so the first character in the string has an index of 0, and so on.

If the string is not found, then this method returns -1.

You can refer to the below code to understand the Javascript String Indexof Method. To call the Javascript String Indexof Method, we are writing the string variable name, followed by the dot, and then the method name(this is going to be followed further) –
As you can see, we have used the indexOf method. The indexOf method returns the first occurrence index of the given string in the string. You can also store it somewhere if you need it further, but for demonstration purposes, we have directly printed it. Have a look at the output →

Also, we know that if the string has never occurred in the given string, then the Javascript String Indexof Method returns the value -1.

As you can see, in the Javascript String Indexof Method, we can pass the string ‘funny’ as an argument, but we know that the argument string is not present there in the given string. So, we get an output of -1. Have a look at the output –

As you can see, we got the output as -1, which was totally expected, since the string has never occurred here in the given string. We can make use of this method, as and when required.

You just need to understand that this method returns the first occurrence index of the given string, in the string, and if the string has never occurred in the given string, then -1 is returned.