What is the string.indexOf() method in TypeScript?

Overview

We can use the indexOf() method in TypeScript to get the index of the first occurrence of a specified sub-string in a given string. This method is also present in JavaScript, owing to the fact that JavaScript is a subset of TypeScript. Hence, they share similar methods.

Syntax

string.indexOf(substring)
Syntax of the indexOf() method of a string

Parameter value

  • substring: This is the substring present in string of which we want to find the starting index.

Return value

The indexOf() method returns an integer. This integer represents the integer of the first occurrence of a particular string. If the sub-string is not found, then a -1 value is returned.

Example

// create some strings
let str1:string = "Edpresso!"
let str2:string = "Educative.io"
let str3:string = "TypeScript is a superset of JavaScript"
let str4:string = "Developer"
// create the substrings to search
let sub1 = "E"
let sub2 = ".io"
let sub3 = "TypeScript"
let sub4 = "se"
// get the first occurring index of substrings
console.log(str1.indexOf(sub1)) // 0
console.log(str2.indexOf(sub2)) // 9
console.log(str3.indexOf(sub3)) // 0
console.log(str4.indexOf(sub4)) // -1 (not found)

Explanation

  • Lines 2–5: We create some strings.
  • Lines 8–11: We create the substrings we want to find.
  • Lines 14–17: We use the indexOf() method to get the index of the first occurrence of the sub-strings and print the results to the console.