How to use JavaScript indexOf() Method? [SOLVED]


Written By - Olorunfemi Akinlua
Advertisement

Getting started with indexOf() Method

The indexOf method is a widely used tool in JavaScript for finding the position of a specified value within an array or a string.

Whether you are working with a long list of data or just a short phrase, the indexOf method can help you locate specific elements or characters within the array or string.

indexOf() starts at the beginning and lastIndexOf() starts at the end. Negative values are allowed for the second argument and are treated as an offset from the end of the array, as they are for the slice() method: a value of -1, for example, specifies the last element of the array.

The following function searches an array for a specified value and returns an array of all matching indexes. This demonstrates how the second argument to indexOf() can be used to find matches beyond the first.

// Find all occurrences of a value x in an array a and return an array
// of matching indexes
function findall(a, x) {
    let results = [],            // The array of indexes we'll return
        len = a.length,          // The length of the array to be searched
        pos = 0;                 // The position to search from
    while(pos < len) {           // While more elements to search...
        pos = a.indexOf(x, pos); // Search
        if (pos === -1) break;   // If nothing found, we're done.
        results.push(pos);       // Otherwise, store index in array
        pos = pos + 1;           // And start next search at next element
    }
    return results;              // Return array of indexes
}

In this article, we will explore how to use the indexOf method with both arrays and strings, including how to specify a starting index for the search and how to use the indexOf method with regular expressions.

 

Using the indexOf method with strings

The indexOf method is a string method in JavaScript that is used to search for a specified value within a string and returns the position of the value within the string. If the value is not found, it returns -1. The indexOf method is case-sensitive, meaning that it will differentiate between uppercase and lowercase characters.

Here's how you can use the indexOf method:

let str = "Hello, World!";

let index = str.indexOf("World");

console.log(index);

Output

Advertisement
7

In the example above, we have a string called str that contains the value "Hello, World!". We then use the indexOf method to search for the value "World" within the string. The indexOf method returns the index (position) of the value within the string, which in this case is 7.

You can also specify a starting index for the search. For example:

let str = "Hello, World!";

let index = str.indexOf("l", 4);

console.log(index);

Output

10

In this example, we search for the first occurrence of the letter "l" in the string, starting at index 4. The indexOf method returns the index of the first occurrence of the letter "l" after index 4, which is 10.

You can also use the indexOf method to search for multiple values within a string. For example:

4
8

In this example, we search for the first occurrence of the letter "o" in the string, and then search for the second occurrence of the letter "o" starting at the index immediately following the first occurrence. The indexOf method returns the index of the first occurrence as 4, and the index of the second occurrence as 7.

You can also use the indexOf method with regular expressions. For example:

let str = "Hello, World!";

let index = str.indexOf("o");
let index2 = str.indexOf("o", index + 1);

console.log(index);
console.log(index2);

Output

Advertisement
4
8

In this example, we use a regular expression to search for the letter "o" in the string. The indexOf method returns the index of the first occurrence of the letter "o" in the string, which is 4.

It's important to note that the indexOf method is not supported in older versions of Internet Explorer (IE8 and below). If you need to support these older browsers, you can use the search method instead.

 

Using the indexOf method with arrays

Here's how you can use the indexOf method with an array:

let arr = [1, 2, 3, 4, 5];

let index = arr.indexOf(3);

console.log(index);

Output

2

In the example above, we have an array called arr that contains the values 1, 2, 3, 4, and 5. We then use the indexOf method to search for the value 3 within the array. The indexOf method returns the index (position) of the value within the array, which in this case is 2.

You can also specify a starting index for the search. For example:

Advertisement
let arr = [1, 2, 3, 4, 5];

let index = arr.indexOf(3, 2);

console.log(index);

Output

2

In this example, we search for the value 3 in the array, starting at index 2. The indexOf method returns the index of the first occurrence of the value 3 after index 2, which is 2.

You can also use the indexOf method to search for multiple values within an array. For example:

let arr = [1, 2, 3, 4, 5, 3];

let index = arr.indexOf(3);
let index2 = arr.indexOf(3, index + 1);

console.log(index);
console.log(index2);

Output

2
5

In this example, we search for the first occurrence of the value 3 in the array, and then search for the second occurrence of the value 3 starting at the index immediately following the first occurrence. The indexOf method returns the index of the first occurrence as 2, and the index of the second occurrence as 5.

 

Summary

The indexOf method is a useful tool in JavaScript for finding the position of a specified value within an array or a string. It can be used to search for a specific element or character within an array or a string, and returns the index (position) of the value within the array or string.

 

References

String.prototype.indexOf() - JavaScript | MDN (mozilla.org)
Array.prototype.indexOf() - JavaScript | MDN (mozilla.org)

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment