NiCk Newman
NiCk Newman

Reputation: 1776

indexOf Matching Confusion

As I'm aware, indexOf searches for the first matched string.

Here is my example code:

Text = 'why/f l';
cmds = {
   "/f l" : ['Friends']
 }

for(var k in cmds){
        if (Text.indexOf(k) == 0){
        console.log('match!');
        console.log('function!' + cmds[k]);
        return // Return and stop!
        }
}

As you can see.. why/f l does not match, but /f l does. Why exactly? I know I could use .match instead, but figured this would be faster. Is it because indexOf only starts the matching process at the beginning of the string at the first character? Bit lost, just trying to get some clarification, thanks!

Upvotes: 0

Views: 59

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

Your test is incorrect. The indexOf method returns (as it name suggests the index of the first match). So if you want to test if k is substring of Text you might want to fix your test:

if (Text.indexOf(k) > -1) {

Here's what the documentation states about it:

The indexOf() method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is not found.

Upvotes: 2

Simba
Simba

Reputation: 1651

IndexOf returns the index of the first character of the matched string, or -1 if there is no match.

So

"abcdef".indexOf("def") would return 3

your if statement reads: if (Text.indexOf(k) == 0)

in plain English this reads as, if Text begins with the string k.

You probably meant if (Text.indexOf(k) != -1)

which in plain English reads as, if Text contains the string k.

Since if Text contains k it will return a positive number, otherwise it will return -1.

Upvotes: 2

Related Questions