[removed] indexOf vs. Match when Searching Strings?

前端 未结 9 1594
感情败类
感情败类 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: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.
    }
    

提交回复
热议问题