Recently while solving some coding problems I ran into a weird situation where i had to check if: String starts with another string
I solved it quite simply with
if(string.includes(substring))
{
//code
}
And it worked..... BUT it returned TRUE when:
const string = "is it you or is it me or what?";
const substring = "is it me or";
What is the reason behind this returning true? I even tried on different compiler websites and they all returned true. I really am puzzled as my understanding of .includes() is that it should check if a string contains the sub-string.
EDIT: I'm actually blind and i didn't notice that it contains the same string in middle of the sentence. Sorry, didn't have much sleep.
If you only need to return true if string starts with substring, use .startsWith() instead. For example:
> 'abc'.startsWith('a')
true
> 'abc'.startsWith('b')
false
Both .contains() (deprecated now, but might be supplied by polyfill) and .includes() (supported universally), however, will return true in both cases, as it checks whether or not a substring is contained within a given string, not necessarily at its beginning:
> 'abc'.includes('a')
true
> 'abc'.includes('b')
true
To answer your specific question, is it me or is part of that bigger string. You can use .indexOf() as a little helper here to provide you the exact position of that string:
const string = "is it you or is it me or what?";
const substring = "is it me or";
string.indexOf(substring); // 13