-1

So i am new to node.js and I have come across this line of code that confuses me:

if (/^\/api\/parsetime/.test(req.url))

I understand the the test() part of it, but only the part before test is odd.

The exercises goal was to do something with the response from the server if the url of the request was to "/api/parsetime".

So basically my question is why is there /^\/, \/ in the url when we put it in a if statement?

Thank you!

BTW, code was taken from NodeSchool workshop (learnyounode). Thank you guys you are awesome!

Pointy
  • 405,095
  • 59
  • 585
  • 614
Roman Timm
  • 65
  • 1
  • 11

1 Answers1

4

That is a regular expression.

The backslashes (\) are escaping the forward slashes (/) so that it doesn't end the pattern before you're done with it.

Antiga
  • 2,264
  • 1
  • 20
  • 28
  • Than what does the ^ do in this case? Can't I just write something like:
    if("/api/parsetime"/.test(req.url)) 
    and be done with it?
    – Roman Timm Dec 08 '15 at 09:43
  • OK I think I get it, thank you :) But one last thing - What will happen if I omit the (^) from the expression? I read on MDN that (^) matches the beginning of the expression but is it necessary? – Roman Timm Dec 08 '15 at 10:06
  • It is necessary because `^` means it has to be the beginning of the expression. So without it, `/cheese/api/parsetime` would also match. Unless you don't care about what comes before it (and you should), then you would want to use that token. – Antiga Dec 08 '15 at 15:42