while going through the JavaScript I just came across .match, .test and .exec
what is the difference?
which is the fastest of all

- 107
- 2
- 5
-
You could start with the documentation ([*match*](http://www.ecma-international.org/ecma-262/6.0/#sec-string.prototype.match), [*test*](http://www.ecma-international.org/ecma-262/6.0/#sec-regexp.prototype.test)), or equivalents on MDN (e.g. search using [*MDN match*](https://www.google.com.au/search?q=MDN+match)). – RobG Feb 10 '16 at 06:14
-
Almost a duplicate: [match Vs exec in JavaScript](http://stackoverflow.com/q/27753246/218196). *"which is the fastest of all"* Not sure that's the right question to ask. Which method to use depends on what you are trying to achieve. They all provide different results. – Felix Kling Feb 10 '16 at 06:53
1 Answers
First off, .exec()
and .test()
are methods on a regular expression object. .match()
is a method on a string and takes a regex object as an argument.
.test()
returns a boolean if there's a match or not. It does not return what actually matches.
.match()
and .exec()
are similar. .match()
is called on the string and returns one set of results. .exec()
is called on the regex and can be called multiple times to return multiple complex matches (when you need multiple matches with groups).
You can see some examples of how you can use multiple successive calls to .exec()
here on MDN.
You would likely use .test()
if you only want to know if it matches or not and don't need to know exactly what matched.
You would likely use .match()
if you want to know what matched and it meets your needs (e.g. you don't need something more complex with multiple calls to .exec()
).

- 683,504
- 96
- 985
- 979