The indexOf(string) function

Personally, 99% of the time, I use indexOf instead of startsWith or endsWith, includes , mainly because I'm very used to it and it's very intuitive. This method will return you the position of your first occurrence of a substring passed, in the given string. If not present, it'll return -1. For instance:

const string = "this is an interesting book and this book is quite good as well.";console.log(string.indexOf("this"))
The output for the preceding code is: 0

This is because the substring is found at the 0th position of the bigger string. If the substring is not present in the string, indexOf returns -1.

Can you come up with a replacement for the startsWith method in terms of indexOf? The following is the answer! ...

Get Learn ECMAScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.