[removed] test vs exec

后端 未结 1 1612
遇见更好的自我
遇见更好的自我 2021-02-20 00:55

I would like to know what\'s the best way to check a string for example (mail, password ..Etc).

/^...$/i.exec(a)

vs

/^...$/i.te         


        
1条回答
  •  囚心锁ツ
    2021-02-20 01:46

    If you only need to test an input string to match a regular expression, RegExp.test is most appropriate. It will give you a boolean return value which makes it ideal for conditions.

    RegExp.exec gives you an array-like return value with all capture groups and matched indexes. Therefore, it is useful when you need to work with the captured groups or indexes after the match. (Also, it behaves a bit different compared to String.match when using the global modifier /g)

    Ultimately, it won't matter much in speed or efficiency. The regular expression will still be evaluated and all matching groups and indexes will be available through the global RegExp object (although it's highly recommended that you use the return values).

    As for the if test, that's just a matter of personal taste. Assigning the result of the regular expression test to a variable with a meaningful name (such as isEmail) could improve the readability, but other than that they're both fine.

    0 讨论(0)
提交回复
热议问题