In this tutorial, you will learn how to find the first occurrence of a character’s position in a string using the JavaScript string indexOf() method.
The indexOf() method in JavaScript is used to find the first occurrence of a character in a given string. It returns the position of the first occurrence of the character in the string. If the character is not found in the string, it returns -1.
The syntax for the indexOf() method is as follows:
str.indexOf(search_value, start) Here, str: The given string search_value: The character or string to search in the given string start: The optional parameter specifies where to start the search in a given string.
Example 1:
Let’s take an example of finding the first occurrence of the “de” character in the string “Hello developers, welcome to the JavaScript tutorial.”
const string = "Hello developers, welcome to the JavaScript tutorial.";<br>const res = string.indexOf("de");<br>console.log("Result of the above code is:-" + res);
Output: Result of the above code is:-6
Example 2:
Now let’s take an example of finding a character or string in a given string with a specific position. In this example, we will find the first occurrence of the “JavaScript” string in the given string starting from position 10.
const string = "Hello JavaScript developers, welcome to the JavaScript tutorial.";<br>const res = string.indexOf("JavaScript", 10);<br>console.log("Result of the above code is:-" + res);
Output: Result of the above code is:-44
In conclusion, the JavaScript string indexOf() method is useful in finding the first occurrence of a character or string in a given string. You can also use the start parameter to start the search from a specific position in the string.