Problem in converting indexOf to a for loop