- JavaScript Array indexOf()
- See Also:
- Syntax
- Parameters
- Return Value
- Note
- More Examples
- Related Pages:
- Browser Support
- Array.prototype.indexOf()
- Try it
- Syntax
- Parameters
- Return value
- Description
- Examples
- Using indexOf()
- Finding all the occurrences of an element
- Finding if an element exists in the array or not and updating the array
- Using indexOf() on sparse arrays
- Calling indexOf() on non-array objects
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- String.prototype.indexOf()
- Try it
- Syntax
- Parameters
- Return value
- Return value when using an empty search string
- Description
- Checking occurrences
- Examples
- Using indexOf()
- indexOf() and case-sensitivity
- Using indexOf() to count occurrences of a letter in a string
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- JavaScript String indexOf()
- Description
- See Also:
- Syntax
- Parameters
- Return Value
- The Differense Between String indexOf() and String search()
- Related Pages
- Browser Support
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
JavaScript Array indexOf()
The indexOf() method returns the first index (position) of a specified value.
The indexOf() method returns -1 if the value is not found.
The indexOf() method starts at a specified index and searches from left to right.
By default the search starts at the first element and ends at the last.
Negative start values counts from the last element (but still searches from left to right).
See Also:
Syntax
Parameters
Parameter | Description |
item | Required. The value to search for. |
start | Optional. Where to start the search. Default value is 0. Negative values start the search from the end of the array. |
Return Value
Note
In an array, the first element has index (position) 0, the second has index 1, .
More Examples
Find the first index of «Apple», starting from the last element:
const fruits = [«Banana», «Orange», «Apple», «Mango», «Apple»];
let index = fruits.indexOf(«Apple», -1);
Related Pages:
Browser Support
indexOf() is an ECMAScript5 (ES5) feature.
ES5 (JavaScript 2009) fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |
Array.prototype.indexOf()
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
Try it
Syntax
indexOf(searchElement) indexOf(searchElement, fromIndex)
Parameters
Element to locate in the array.
Zero-based index at which to start searching, converted to an integer.
Return value
The first index of the element in the array; -1 if not found.
Description
The indexOf() method compares searchElement to elements of the array using strict equality (the same algorithm used by the === operator). NaN values are never compared as equal, so indexOf() always returns -1 when searchElement is NaN .
The indexOf() method skips empty slots in sparse arrays.
The indexOf() method is generic. It only expects the this value to have a length property and integer-keyed properties.
Examples
Using indexOf()
The following example uses indexOf() to locate values in an array.
const array = [2, 9, 9]; array.indexOf(2); // 0 array.indexOf(7); // -1 array.indexOf(9, 2); // 2 array.indexOf(2, -1); // -1 array.indexOf(2, -3); // 0
You cannot use indexOf() to search for NaN .
const array = [NaN]; array.indexOf(NaN); // -1
Finding all the occurrences of an element
const indices = []; const array = ["a", "b", "a", "c", "a", "d"]; const element = "a"; let idx = array.indexOf(element); while (idx !== -1) indices.push(idx); idx = array.indexOf(element, idx + 1); > console.log(indices); // [0, 2, 4]
Finding if an element exists in the array or not and updating the array
function updateVegetablesCollection(veggies, veggie) if (veggies.indexOf(veggie) === -1) veggies.push(veggie); console.log(`New veggies collection is: $veggies>`); > else console.log(`$veggie> already exists in the veggies collection.`); > > const veggies = ["potato", "tomato", "chillies", "green-pepper"]; updateVegetablesCollection(veggies, "spinach"); // New veggies collection is: potato,tomato,chillies,green-pepper,spinach updateVegetablesCollection(veggies, "spinach"); // spinach already exists in the veggies collection.
Using indexOf() on sparse arrays
You cannot use indexOf() to search for empty slots in sparse arrays.
.log([1, , 3].indexOf(undefined)); // -1
Calling indexOf() on non-array objects
The indexOf() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length .
const arrayLike = length: 3, 0: 2, 1: 3, 2: 4, 3: 5, // ignored by indexOf() since length is 3 >; console.log(Array.prototype.indexOf.call(arrayLike, 2)); // 0 console.log(Array.prototype.indexOf.call(arrayLike, 5)); // -1
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Jun 27, 2023 by MDN contributors.
Your blueprint for a better internet.
String.prototype.indexOf()
The indexOf() method of String values searches this string and returns the index of the first occurrence of the specified substring. It takes an optional starting position and returns the first occurrence of the specified substring at an index greater than or equal to the specified number.
Try it
Syntax
indexOf(searchString) indexOf(searchString, position)
Parameters
Substring to search for. All values are coerced to strings, so omitting it or passing undefined causes indexOf() to search for the string «undefined» , which is rarely what you want.
The method returns the index of the first occurrence of the specified substring at a position greater than or equal to position , which defaults to 0 . If position is greater than the length of the calling string, the method doesn’t search the calling string at all. If position is less than zero, the method behaves as it would if position were 0 .
- ‘hello world hello’.indexOf(‘o’, -5) returns 4 — because it causes the method to behave as if the second argument were 0 , and the first occurrence of o at a position greater or equal to 0 is at position 4 .
- ‘hello world hello’.indexOf(‘world’, 12) returns -1 — because, while it’s true the substring world occurs at index 6 , that position is not greater than or equal to 12 .
- ‘hello world hello’.indexOf(‘o’, 99) returns -1 — because 99 is greater than the length of hello world hello , which causes the method to not search the string at all.
Return value
The index of the first occurrence of searchString found, or -1 if not found.
Return value when using an empty search string
Searching for an empty search string produces strange results. With no second argument, or with a second argument whose value is less than the calling string’s length, the return value is the same as the value of the second argument:
"hello world".indexOf(""); // returns 0 "hello world".indexOf("", 0); // returns 0 "hello world".indexOf("", 3); // returns 3 "hello world".indexOf("", 8); // returns 8
However, with a second argument whose value is greater than or equal to the string’s length, the return value is the string’s length:
"hello world".indexOf("", 11); // returns 11 "hello world".indexOf("", 13); // returns 11 "hello world".indexOf("", 22); // returns 11
In the former instance, the method behaves as if it found an empty string just after the position specified in the second argument. In the latter instance, the method behaves as if it found an empty string at the end of the calling string.
Description
Strings are zero-indexed: The index of a string’s first character is 0 , and the index of a string’s last character is the length of the string minus 1.
"Blue Whale".indexOf("Blue"); // returns 0 "Blue Whale".indexOf("Blute"); // returns -1 "Blue Whale".indexOf("Whale", 0); // returns 5 "Blue Whale".indexOf("Whale", 5); // returns 5 "Blue Whale".indexOf("Whale", 7); // returns -1 "Blue Whale".indexOf(""); // returns 0 "Blue Whale".indexOf("", 9); // returns 9 "Blue Whale".indexOf("", 10); // returns 10 "Blue Whale".indexOf("", 11); // returns 10
The indexOf() method is case sensitive. For example, the following expression returns -1 :
"Blue Whale".indexOf("blue"); // returns -1
Checking occurrences
When checking if a specific substring occurs within a string, the correct way to check is test whether the return value is -1 :
"Blue Whale".indexOf("Blue") !== -1; // true; found 'Blue' in 'Blue Whale' "Blue Whale".indexOf("Bloe") !== -1; // false; no 'Bloe' in 'Blue Whale'
Examples
Using indexOf()
The following example uses indexOf() to locate substrings in the string «Brave new world» .
const str = "Brave new world"; console.log(str.indexOf("w")); // 8 console.log(str.indexOf("new")); // 6
indexOf() and case-sensitivity
The following example defines two string variables.
The variables contain the same string, except that the second string contains uppercase letters. The first console.log() method displays 19 . But because the indexOf() method is case sensitive, the string «cheddar» is not found in myCapString , so the second console.log() method displays -1 .
const myString = "brie, pepper jack, cheddar"; const myCapString = "Brie, Pepper Jack, Cheddar"; console.log(myString.indexOf("cheddar")); // 19 console.log(myCapString.indexOf("cheddar")); // -1
Using indexOf() to count occurrences of a letter in a string
The following example sets count to the number of occurrences of the letter e in the string str :
const str = "To be, or not to be, that is the question."; let count = 0; let position = str.indexOf("e"); while (position !== -1) count++; position = str.indexOf("e", position + 1); > console.log(count); // 4
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Apr 28, 2023 by MDN contributors.
Your blueprint for a better internet.
JavaScript String indexOf()
Find the first occurrence of «e», starting at position 5:
Find the first occurrence of «a»:
Description
The indexOf() method returns the position of the first occurrence of a value in a string.
The indexOf() method returns -1 if the value is not found.
The indexOf() method is case sensitive.
See Also:
Syntax
Parameters
Parameter | Description |
searchvalue | Required. The string to search for. |
start | Optional. The position to start from (default is 0). |
Return Value
The Differense Between
String indexOf() and String search()
The indexOf() method cannot search against a regular expression.
The search() cannot take a start position argument.
Related Pages
Browser Support
indexOf() is an ECMAScript1 (ES1) feature.
ES1 (JavaScript 1997) is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.