I’m doing a pretty basic string matching test as follows:
if(msList.indexOf(textChoice) != -1)
This works well except that occasionally the sub-string I’m looking for (textChoice) ends with an asterisk. Then I end up getting false matches because the asterisk in the string is interpreted as an operator, not a character in the string.
So how can I do this test so that any asterisks in the sub-string are treated as regular characters?
PS. I know the simple answer is “Don’t include asterisks in your sub-string” but they’re in the data I’m working with–I can’t get rid of them.
All characters in the substring will be treated as regular characters.
*is not a special operator and does not change the behavior ofindexOfin any way. Moreover, theindexOfmethod should never returnfalse. It will return:-1if no match is found orNote that the starting index can be
0which does not equate to false for substring searching. It just means that the substring was found in the beginning of the string.Put explicit checks comparing the return value with
-1instead of just checking for a truthy value.Instead, always do this: