[removed] indexOf vs. Match when Searching Strings?

前端 未结 9 1560
感情败类
感情败类 2020-12-04 13:16

Readability aside, are there any discernable differences (performance perhaps) between using

str.indexOf("src") 

and



        
相关标签:
9条回答
  • 2020-12-04 13:35

    If you're trying to search for substring occurrences case-insensitively then match seems to be faster than a combination of indexOf and toLowerCase()

    Check here - http://jsperf.com/regexp-vs-indexof/152

    0 讨论(0)
  • 2020-12-04 13:38

    RegExp is indeed slower than indexOf (you can see it here), though normally this shouldn't be an issue. With RegExp, you also have to make sure the string is properly escaped, which is an extra thing to think about.

    Both of those issues aside, if two tools do exactly what you need them to, why not choose the simpler one?

    0 讨论(0)
  • 2020-12-04 13:41

    The return values are different

    Aside from the performance implications, which are addressed by other answers, it is important to note that the return values for each method are different; so the methods cannot merely be substituted without also changing your logic.

    Return value of .indexOf: integer

    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.

    Return value of .match: array

    An Array containing the entire match result and any parentheses-captured matched results.
    Returns null if there were no matches.

    Because .indexOf returns 0 if the calling string begins with the specified value, a simple truthy test will fail.

    For example:

    Given this class…

    class='DisablesGuiClass-2345-2d73-83hf-8293 redBorder' 
    

    …the return values for each would differ:

    //  returns `0`, evaluates to `false`
    if (string.indexOf('DisablesGuiClass-')) {
        … // this block is skipped.
    }
    

    vs.

    //  returns `["DisablesGuiClass-"]`, evaluates to `true`
    if (string.match(/DisablesGuiClass-/)) { 
        … // this block is run.
    }
    

    The correct way to run a truthy test with the return from .indexOf is to test against -1:

    if (string.indexOf('DisablesGuiClass-') !== -1) {
    //  ^returns `0`                        ^evaluates to `true`
        … // this block is run.
    }
    
    0 讨论(0)
提交回复
热议问题