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.
string.indexOf(substring)
substring
: This is the substring present in string
of which we want to find the starting index.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.
// create some stringslet 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 searchlet sub1 = "E"let sub2 = ".io"let sub3 = "TypeScript"let sub4 = "se"// get the first occurring index of substringsconsole.log(str1.indexOf(sub1)) // 0console.log(str2.indexOf(sub2)) // 9console.log(str3.indexOf(sub3)) // 0console.log(str4.indexOf(sub4)) // -1 (not found)
indexOf()
method to get the index of the first occurrence of the sub-strings and print the results to the console.