[removed] indexOf vs. Match when Searching Strings?

前端 未结 9 1585
感情败类
感情败类 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:25

    You ask whether str.indexOf('target') or str.match(/target/) should be preferred. As other posters have suggested, the use cases and return types of these methods are different. The first asks "where in str can I first find 'target'?" The second asks "does str match the regex and, if so, what are all of the matches for any associated capture groups?"

    The issue is that neither one technically is designed to ask the simpler question "does the string contain the substring?" There is something that is explicitly designed to do so:

    var doesStringContainTarget = /target/.test(str);
    

    There are several advantages to using regex.test(string):

    1. It returns a boolean, which is what you care about
    2. It is more performant than str.match(/target/) (and rivals str.indexOf('target'))
    3. If for some reason, str is undefined or null, you'll get false (the desired result) instead of throwing a TypeError

提交回复
热议问题