Exploring the JavaScript String indexOf() Method
In this blog post, we will delve into the details of the indexOf() method in JavaScript. This method is used to determine the position of the first occurrence of a specified string within another string. If the desired string is not found, it returns -1.
Let’s take a look at some examples to understand how this method works:
1 | 'JavaScript'.indexOf('Script') // Output: 4 |
In the first example, we search for the position of the string ‘Script’ within the string ‘JavaScript’. Since ‘Script’ starts at index 4, the output is 4.
Similarly, in the second example, the complete string ‘JavaScript’ starts at index 0, so the output is 0.
In the third example, the substring ‘aSc’ starts at index 3 in the string ‘JavaScript’, resulting in an output of 3.
Lastly, in the fourth example, the string ‘C++’ is not found within ‘JavaScript’, so the output is -1.
Besides the basic usage, you can also provide an optional second parameter to indexOf(). This parameter specifies the starting point for the search. Let’s explore some examples:
1 | 'a nice string'.indexOf('nice') !== -1 // Output: true |
In the first example, we search for the string ‘nice’ within the string ‘a nice string’. Since ‘nice’ is found starting at index 2, the output is true.
In the second example, we set the starting point to index 3. However, ‘nice’ is not found starting from that position, resulting in a false output.
Lastly, in the third example, we start the search from index 2, where ‘nice’ is found. Hence, the output is true.
To summarize, the indexOf() method in JavaScript allows you to locate the position of a specified string within another string. It is a powerful tool for string manipulation and searching.
Tags: JavaScript, String methods, indexOf()