Many times I’m using the string match function to know if a string matches a regular expression.
if(str.match(/{regex}/))
Is there any difference between this:
if (/{regex}/.test(str))
They seem to give the same result?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Basic Usage
First, let’s see what each function does:
regexObject.test( String )
string.match( RegExp )
Since
nullevaluates tofalse,Performance
Is there any difference regarding performance?
Yes. I found this short note in the MDN site:
Is the difference significant?
The answer once more is YES! This jsPerf I put together shows the difference is ~30% – ~60% depending on the browser:
Conclusion
Use
.testif you want a faster boolean check. Use.matchto retrieve all matches when using thegglobal flag.