VOOZH about

URL: https://www.geeksforgeeks.org/typescript/typescript-string-indexof-method/

⇱ TypeScript String indexOf() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

TypeScript String indexOf() Method

Last Updated : 15 Jul, 2024

The indexOf() method in TypeScript is an inbuilt function used to find the index of the first occurrence of a specified value within a calling string. If the value is not found, it returns -1.

Syntax

string.indexOf(searchValue[, fromIndex]) 

Parameter: This method accepts two parameters as mentioned above and described below. 

  • searchValue: This parameter is a string representing the value to search for.
  • fromIndex: This parameter is a location within the calling string to start the search from.

Return Value: This method returns the index of the found occurrence, otherwise -1 if not found.

The below example illustrates the  String indexOf() method in TypeScriptJS:

Example 1: Finding a Substring

In this example we finds the position of "world" in the string str using indexOf, which returns 21 because world starts at the 21st character (0-based index).

Output:

21

Example 2: Substring Not Found

In this example we searches for JavaScript in str using indexOf, returning -1 because JavaScript is not found within the string.

Output:

-1
Comment
Article Tags:
Article Tags:

Explore