1

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.

user3167857
  • 55
  • 1
  • 10
  • no.These are different – RIYAJ KHAN Jun 24 '16 at 07:10
  • _can we use both interchangeably in our code?_ **Yes** since `null` and `false` are both falsy value. **NO** if you're comparing result with `false` or `null`. Check if pattern exists in a string use `test()`. Get the string matched by pattern, use `match()`. – Tushar Jun 24 '16 at 07:11
  • test() returns a boolean, match() returns null or an array. if you don't need the matching results, test() is faster. – dandavis Jun 24 '16 at 07:11
  • can you please explain when we are using these(like real case scenerios)? – user3167857 Jun 24 '16 at 07:12

3 Answers3

1

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

Community
  • 1
  • 1
Aditya Singh
  • 15,810
  • 15
  • 45
  • 67
1

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

Dev Try
  • 211
  • 2
  • 14
0

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!

Community
  • 1
  • 1
Ragu Natarajan
  • 709
  • 3
  • 16