Is there any difference between test() and match()?
I know both are used for searching a match in a string. My question is can we use both interchangeably in our code?
Thanks in advance.
Is there any difference between test() and match()?
I know both are used for searching a match in a string. My question is can we use both interchangeably in our code?
Thanks in advance.
Yes. .test()
is for RegExp while .match
is intended for strings
.match()
The match() method retrieves the matches when matching a string against a regular expression. Syntax:
str.match(regexp)
.test()
The test() method executes a search for a match between a regular expression and a specified string. Returns true or false. Syntax:
regexObj.test(str)
For a more detailed explanation on this, refer this SO answer: https://stackoverflow.com/a/10940138/3878940
MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
.test() - returns a Boolean whether there is a match or not. It never returns what actually matches. .match() - is a method on a string and returns one set of results.
This questions already discussed. Please refer this below link. I hope it will help you.
regex.test V.S. string.match to know if a string matches a regular expression
Thank you!