Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between .match and .test in javascript [closed]

Tags:

javascript

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

like image 714
Kuladeep sony Avatar asked Feb 10 '16 06:02

Kuladeep sony


People also ask

What does .test do in JavaScript?

test() The test() method executes a search for a match between a regular expression and a specified string. Returns true or false .

What does .match do in JavaScript?

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.

Which is faster RegExp match or RegExp test?

Use . test if you want a faster boolean check. Use . match to retrieve all matches when using the g global flag.

How do you check whether a string matches a regex in JavaScript?

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.


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

like image 84
jfriend00 Avatar answered Nov 09 '22 04:11

jfriend00