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
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.