Which method returns the index of the position of the first occurrence of a specified text in a string?

Which method returns the index of the position of the first occurrence of a specified text in a string?

This JavaScript tutorial explains how to use the string method called indexOf() with syntax and examples.

In JavaScript, indexOf() is a string method that is used to find the location of a substring in a string. Because the indexOf() method is a method of the String object, it must be invoked through a particular instance of the String class.

In JavaScript, the syntax for the indexOf() method is:

string.indexOf(substring [, start_position]);

Parameters or Arguments

substring It is the substring that you want to find within string. start_position Optional. It is the position in string where the search will start. The first position in string is 0. If this parameter is not provided, the search will start at the beginning of string and the full string will be searched.

The indexOf() method returns the position of the first occurrence of substring in string. The first position in the string is 0.

If the indexOf() method does not find the substring in string, it will return -1.

Note

  • The indexOf() method performs a case-sensitive search.
  • The indexOf() method does not change the value of the original string.

Let's take a look at an example of how to use the indexOf() method in JavaScript.

For example:

var totn_string = 'TechOnTheNet'; console.log(totn_string.indexOf('t'));

In this example, we have declared a variable called totn_string that is assigned the string value of 'TechOnTheNet'. We have then invoked the indexOf() method of the totn_string variable to look for a substring within totn_string.

We have written the output of the indexOf() method to the web browser console log, for demonstration purposes, to show what the indexOf() method returns.

The following will be output to the web browser console log:

11

In this example, the indexOf() method returned 11 because the first occurrence of 't' within 'TechOnTheNet' is position 11 in the string.

Specifying a Start Position Parameter

You can change the position where the search will start in the string by providing a start_position parameter to the indexOf() method.

For example:

var totn_string = 'TechOnTheNet'; console.log(totn_string.indexOf('T',4));

The following will be output to the web browser console log:

6

In this example, we have set the start_position parameter to a value of 4. This means that the search will begin looking for the value 'T' starting at position 4 in the string. So in this case, the substring 'T' is found at position 6 in the string 'TechOnTheNet'.

Specifying Multiple Characters as the Substring

Next, the indexOf() method can search for multiple characters in a string.

For example:

var totn_string = 'TechOnTheNet'; console.log(totn_string.indexOf('The'));

The following will be output to the web browser console log:

6

In this example, the indexOf() method returned 6 which is the position of 'The' in the string 'TechOnTheNet'.

Since the indexOf() method can only return one value, it will return the position of the substring's first character when the occurrence is found, even though the substring is multiple characters in length.

No Occurrence is Found

Finally, the indexOf() method will return -1 if an occurrence of substring is not found in string.

For example:

var totn_string = 'TechOnTheNet'; console.log(totn_string.indexOf('z'));

The following will be output to the web browser console log:

-1

In this example, the indexOf() method returned -1 because the substring 'z' is not found in the string 'TechOnTheNet'.

public: int IndexOf(char value, int startIndex, int count); public int IndexOf (char value, int startIndex, int count); member this.IndexOf : char * int * int -> int Public Function IndexOf (value As Char, startIndex As Integer, count As Integer) As Integer Int32

The zero-based index position of value from the start of the string if that character is found, or -1 if it is not.

Examples

The following example demonstrates the IndexOf method.

// Example for the String::IndexOf( Char, int, int ) method. using namespace System; void FindAllChar( Char target, String^ searched ) { Console::Write( "The character '{0}' occurs at position(s): ", target ); int startIndex = -1; int hitCount = 0; // Search for all occurrences of the target. while ( true ) { startIndex = searched->IndexOf( target, startIndex + 1, searched->Length - startIndex - 1 ); // Exit the loop if the target is not found. if ( startIndex < 0 ) break; Console::Write( "{0}, ", startIndex ); hitCount++; } Console::WriteLine( "occurrences: {0}", hitCount ); } int main() { String^ br1 = "0----+----1----+----2----+----3----+----" "4----+----5----+----6----+----7"; String^ br2 = "0123456789012345678901234567890123456789" "0123456789012345678901234567890"; String^ str = "ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi " "ABCDEFGHI abcdefghi ABCDEFGHI"; Console::WriteLine( "This example of String::IndexOf( Char, int, int )\n" "generates the following output." ); Console::WriteLine( "{0}{1}{0}{2}{0}{3}{0}", Environment::NewLine, br1, br2, str ); FindAllChar( 'A', str ); FindAllChar( 'a', str ); FindAllChar( 'I', str ); FindAllChar( 'i', str ); FindAllChar( '@', str ); FindAllChar( ' ', str ); } /* This example of String::IndexOf( Char, int, int ) generates the following output. 0----+----1----+----2----+----3----+----4----+----5----+----6----+----7 01234567890123456789012345678901234567890123456789012345678901234567890 ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi ABCDEFGHI The character 'A' occurs at position(s): 0, 20, 40, 60, occurrences: 4 The character 'a' occurs at position(s): 10, 30, 50, occurrences: 3 The character 'I' occurs at position(s): 8, 28, 48, 68, occurrences: 4 The character 'i' occurs at position(s): 18, 38, 58, occurrences: 3 The character '@' occurs at position(s): occurrences: 0 The character ' ' occurs at position(s): 9, 19, 29, 39, 49, 59, occurrences: 6 */ // Example for the String.IndexOf( char, int, int ) method. using System; class IndexOfCII { public static void Main() { string br1 = "0----+----1----+----2----+----3----+----" + "4----+----5----+----6----+----7"; string br2 = "0123456789012345678901234567890123456789" + "0123456789012345678901234567890"; string str = "ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi " + "ABCDEFGHI abcdefghi ABCDEFGHI"; Console.WriteLine( "This example of String.IndexOf( char, int, int )\n" + "generates the following output." ); Console.WriteLine( "{0}{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str ); FindAllChar( 'A', str ); FindAllChar( 'a', str ); FindAllChar( 'I', str ); FindAllChar( 'i', str ); FindAllChar( '@', str ); FindAllChar( ' ', str ); } static void FindAllChar( Char target, String searched ) { Console.Write( "The character '{0}' occurs at position(s): ", target ); int startIndex = -1; int hitCount = 0; // Search for all occurrences of the target. while( true ) { startIndex = searched.IndexOf( target, startIndex + 1, searched.Length - startIndex - 1 ); // Exit the loop if the target is not found. if( startIndex < 0 ) break; Console.Write( "{0}, ", startIndex ); hitCount++; } Console.WriteLine( "occurrences: {0}", hitCount ); } } /* This example of String.IndexOf( char, int, int ) generates the following output. 0----+----1----+----2----+----3----+----4----+----5----+----6----+----7 01234567890123456789012345678901234567890123456789012345678901234567890 ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi ABCDEFGHI The character 'A' occurs at position(s): 0, 20, 40, 60, occurrences: 4 The character 'a' occurs at position(s): 10, 30, 50, occurrences: 3 The character 'I' occurs at position(s): 8, 28, 48, 68, occurrences: 4 The character 'i' occurs at position(s): 18, 38, 58, occurrences: 3 The character '@' occurs at position(s): occurrences: 0 The character ' ' occurs at position(s): 9, 19, 29, 39, 49, 59, occurrences: 6 */ // Example for the String.IndexOf( char, int, int ) method. open System let br1 = "0----+----1----+----2----+----3----+----" + "4----+----5----+----6----+----7" let br2 = "0123456789012345678901234567890123456789" + "0123456789012345678901234567890" let str = "ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi " + "ABCDEFGHI abcdefghi ABCDEFGHI" printfn "This example of String.IndexOf( char, int, int )\ngenerates the following output." printfn $"{Environment.NewLine}{br1}{Environment.NewLine}{br2}{Environment.NewLine}{str}{Environment.NewLine}" let findAllChar (target: char) (searched: string) = printf $"The character '{target}' occurs at position(s): " let mutable hitCount = 0 let mutable startIndex = -1 let mutable broken = false // Search for all occurrences of the target. while not broken do startIndex <- searched.IndexOf(target, startIndex + 1, searched.Length - startIndex - 1) // Exit the loop if the target is not found. if startIndex < 0 then broken <- true else printf $"{startIndex}, " hitCount <- hitCount + 1 printfn $"occurrences: {hitCount}" findAllChar 'A' str findAllChar 'a' str findAllChar 'I' str findAllChar 'i' str findAllChar '@' str findAllChar ' ' str (* This example of String.IndexOf( char, int, int ) generates the following output. 0----+----1----+----2----+----3----+----4----+----5----+----6----+----7 01234567890123456789012345678901234567890123456789012345678901234567890 ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi ABCDEFGHI The character 'A' occurs at position(s): 0, 20, 40, 60, occurrences: 4 The character 'a' occurs at position(s): 10, 30, 50, occurrences: 3 The character 'I' occurs at position(s): 8, 28, 48, 68, occurrences: 4 The character 'i' occurs at position(s): 18, 38, 58, occurrences: 3 The character '@' occurs at position(s): occurrences: 0 The character ' ' occurs at position(s): 9, 19, 29, 39, 49, 59, occurrences: 6 *) ' Example for the String.IndexOf( Char, Integer, Integer ) method. Module IndexOfCII Sub Main() Dim br1 As String = _ "0----+----1----+----2----+----3----+----" & _ "4----+----5----+----6----+----7" Dim br2 As String = _ "0123456789012345678901234567890123456789" & _ "0123456789012345678901234567890" Dim str As String = _ "ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi " & _ "ABCDEFGHI abcdefghi ABCDEFGHI" Console.WriteLine( _ "This example of String.IndexOf( Char, Integer, Integer )" & _ vbCrLf & "generates the following output." ) Console.WriteLine( _ "{0}{1}{0}{2}{0}{3}{0}", _ Environment.NewLine, br1, br2, str) FindAllChar("A"c, str) FindAllChar("a"c, str) FindAllChar("I"c, str) FindAllChar("i"c, str) FindAllChar("@"c, str) FindAllChar(" "c, str) End Sub Sub FindAllChar(target As Char, searched As String) Console.Write( _ "The character ""{0}"" occurs at position(s): ", target) Dim startIndex As Integer = - 1 Dim hitCount As Integer = 0 ' Search for all occurrences of the target. While True startIndex = searched.IndexOf( _ target, startIndex + 1, _ searched.Length - startIndex - 1) ' Exit the loop if the target is not found. If startIndex < 0 Then Exit While End If Console.Write("{0}, ", startIndex) hitCount += 1 End While Console.WriteLine("occurrences: {0}", hitCount) End Sub End Module 'IndexOfCII ' This example of String.IndexOf( Char, Integer, Integer ) ' generates the following output. ' ' 0----+----1----+----2----+----3----+----4----+----5----+----6----+----7 ' 01234567890123456789012345678901234567890123456789012345678901234567890 ' ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi ABCDEFGHI ' ' The character "A" occurs at position(s): 0, 20, 40, 60, occurrences: 4 ' The character "a" occurs at position(s): 10, 30, 50, occurrences: 3 ' The character "I" occurs at position(s): 8, 28, 48, 68, occurrences: 4 ' The character "i" occurs at position(s): 18, 38, 58, occurrences: 3 ' The character "@" occurs at position(s): occurrences: 0 ' The character " " occurs at position(s): 9, 19, 29, 39, 49, 59, occurrences: 6

Remarks

The search begins at startIndex and continues to startIndex + count -1. The character at startIndex + count is not included in the search.

Index numbering starts from 0 (zero). The startIndex parameter can range from 0 to the length of the string instance.

This method performs an ordinal (culture-insensitive) search, where a character is considered equivalent to another character only if their Unicode scalar values are the same. To perform a culture-sensitive search, use the CompareInfo.IndexOf method, where a Unicode scalar value representing a precomposed character, such as the ligature "Æ" (U+00C6), might be considered equivalent to any occurrence of the character's components in the correct sequence, such as "AE" (U+0041, U+0045), depending on the culture.

See also

  • Char
  • Int32
  • IndexOfAny(Char[])
  • LastIndexOf(Char)
  • LastIndexOfAny(Char[])

Applies to