while going through the JavaScript I just came across .match, .test and .exec
what is the difference?
which is the fastest of all
test() The test() method executes a search for a match between a regular expression and a specified string. Returns true or false .
JavaScript match() Function. The string. match() is an inbuilt function in JavaScript used to search a string for a match against any regular expression. If the match is found, then this will return the match as an array.
Use . test if you want a faster boolean check. Use . match to retrieve all matches when using the g global flag.
If you need to know if a string matches a regular expression RegExp , use RegExp.prototype.test() . If you only want the first match found, you might want to use RegExp.prototype.exec() instead.
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()
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With