javascriptindexof

Javascript, string: test string for presence of sub-string that includes an asterisk (*)


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.


Solution

  • All characters in the substring will be treated as regular characters. * is not a special operator and does not change the behavior of indexOf in any way. Moreover, the indexOf method should never return false. It will return:

    Note that the starting index can be 0 which does not equate to false for substring searching. It just means that the substring was found in the beginning of the string.

    "ABC".indexOf("AB") // 0
    

    Put explicit checks comparing the return value with -1 instead of just checking for a truthy value.

    if("ABC".indexOf("AB")) {
        // will never execute
    }
    

    Instead, always do this:

    if("ABC".indexOf("AB") != -1) {
       // ..
    }