String.prototype.indexOf()

Esta tradução está incompleta. Ajude atraduzir este artigo.

Sumário

The indexOf() method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is not found.

Sintaxe

str.indexOf(searchValue[, fromIndex])

Parametros

searchValue
A string representing the value to search for.
fromIndex
The location within the calling string to start the search from. It can be any integer. The default value is 0. If fromIndex < 0 the entire string is searched (same as passing 0). If fromIndex >= searchValue.length, the method will return -1.

Descrição

Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character of a string called stringName is stringName.length - 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("", 9);      // returns  9
"Blue Whale".indexOf("", 10);     // returns 10
"Blue Whale".indexOf("", 11);     // returns 10

Case-sensitivity

The indexOf method is case sensitive. For example, the following expression returns -1:

"Blue Whale".indexOf("blue") // returns -1

Checking occurrences

Note that '0' doesn't evaluate to true and '-1' doesn't evaluate to false. Therefore, when checking if a specific string exists within another string the correct way to check would be:

"Blue Whale".indexOf("Blue") != -1; // true
"Blue Whale".indexOf("Bloe") != -1; // false

Exemplos

Exemplo: Usando indexOf e lastIndexOf

The following example uses indexOf and lastIndexOf to locate values in the string "Brave new world".

var anyString = "Brave new world";

console.log("The index of the first w from the beginning is " + anyString.indexOf("w"));
// Displays 8
console.log("The index of the first w from the end is " + anyString.lastIndexOf("w")); 
// Displays 10

console.log("The index of 'new' from the beginning is " + anyString.indexOf("new"));   
// Displays 6
console.log("The index of 'new' from the end is " + anyString.lastIndexOf("new"));
// Displays 6

Exemplo: indexOf e 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 log method displays 19. But because the indexOf method is case sensitive, the string "cheddar" is not found in myCapString, so the second log method displays -1.

var myString    = "brie, pepper jack, cheddar";
var myCapString = "Brie, Pepper Jack, Cheddar";

console.log('myString.indexOf("cheddar") is ' + myString.indexOf("cheddar"));    
// Displays 19
console.log('myCapString.indexOf("cheddar") is ' + myCapString.indexOf("cheddar")); 
// Displays -1

Exemplo: Usando indexOf para contar as ocorrencias de uma letra numa string.

The following example sets count to the number of occurrences of the letter x in the string str:

count = 0;
pos = str.indexOf("x");

while ( pos != -1 ) {
   count++;
   pos = str.indexOf( "x",pos + 1 );
}

Especificações

Specification Status Comment
ECMAScript 1st Edition. Standard Initial definition.
ECMAScript 5.1 (ECMA-262)
The definition of 'String.prototype.indexOf' in that specification.
Standard  
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'String.prototype.indexOf' in that specification.
Standard  

Compatibilidade em navegadores

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

Veja também

Etiquetas do documento e colaboradores

 Colaboradores desta página: diegoarcega, teoli, nicholasess
 Última atualização por: diegoarcega,