Start learning free

LESSON 68 OF 675 · STRINGS I

String Find in TypeScript

Lesson

In TypeScript, you can find the index of a substring using indexOf():

s.indexOf(sub)         // returns index of first occurrence, or -1 if not found
s.lastIndexOf(sub)     // returns index of last occurrence
s.indexOf(sub, start)  // search starting from index `start`

Here are some examples:

let sentence = "Hello World";
let idx = sentence.indexOf("World");
console.log(idx);  // 6

console.log(sentence.indexOf("xyz"));  // -1  (not found)

The index returned is the position of the first character of the found substring.


Assignment
Follow the Coding Tutorial and find the index of "World" in sentence!


Hint
Use sentence.indexOf("World") and assign the result to idx.

STEP 1 OF 1
    Ctrl + Enter to check