Ant's Ant's - 1 year ago 94
Javascript Question

What is the need for caret (^) and dollar symbol ($) in regular expression in JS?

I have read recently about Java Script regular expressions, but i have got confused.

My author says that it is must to include the caret (

) and dollar symbol (
) at the beginning and end of the all regular expressions declarations? Why this is needed actually? Whats its purpose?

Correct me if am wrong!

Answer Source

Javascript RegExp() allows you to specify a multi-line mode (m) which changes the behavior of ^ and $.

^ represents the start of the current line in multi-line mode, otherwise the start of the string

$ represents the end of the current line in multi-line mode, otherwise the end of the string

For example: this allows you to match something like semicolons at the end of a line where the next line starts with "var" /;$\n\s*var/m

Fast regexen also need an "anchor" point, somewhere to start it's search somewhere in the string. These characters tell the Regex engine where to start looking and generally reduce the number of backtracks, making your Regex much, much faster in many cases.

NOTE: This knowledge came from Nicolas Zakas's High Performance Javascript

Conclusion: You should use them!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download