-1

I made this so only messages starting with '/msg' or '/logout' will submit.

But, users can still send messages! Is something wrong with my code?

if ((msg.indexOf("/msg") != 0) && (msg.indexOf("/logout") != 0))
{
    return;
}
Dav
  • 150
  • 9

2 Answers2

4

indexOf will return -1 if the String is not found otherwise it will return the index found which is >= 0

So your test have to be:

if ((msg.indexOf("/msg") < 0) && (msg.indexOf("/logout") < 0))
{
 return;
}

or

if ((msg.indexOf("/msg") == -1) && (msg.indexOf("/logout") == -1))
{
 return;
}
Patrick
  • 15,702
  • 1
  • 39
  • 39
  • The question states that only messages __starting__ with "/msg" and "/logout" are acceptable (`indexOf` returns 0). Your solution will accept these strings _anywhere_ in `msg`... – calebds Feb 06 '12 at 19:16
  • P.S. -- this works just like the OP's code, but accepts MORE messages and is thus incorrect. I believe the problem must lie elsewhere. – calebds Feb 06 '12 at 19:26
  • Turns out my code did work. The issue was in code I neglected to show you but I fixed it. Thanks for the help anyway and yeah glad you caught it too. :) In 8 hours do I accept an answer or answer it myself or what? – Dav Feb 06 '12 at 19:39
0

Turns out my code did work. The issue was in code I neglected to show you but I fixed it.

Thanks for the help anyway. :)

Dav
  • 150
  • 9