Use this lesson to learn Anchors: string start ^ and end $ in JavaScript. It belongs to the Regular expressions chapter inside Additional articles, so it fits naturally into a complete JavaScript course from core language concepts to browser APIs.
The caret ^ and dollar $ characters have special meaning in a regexp. They are called “anchors”.
The caret ^ matches at the beginning of the text, and the dollar $ – at the end.
For instance, let’s test if the text starts with Mary:
javascript
letstr1 ="Mary had a little lamb";alert(/^Mary/.test(str1));// true
The pattern ^Mary means: “string start and then Mary”.
Similar to this, we can test if the string ends with snow using snow$:
javascript
letstr1 ="its fleece was white as snow";alert(/snow$/.test(str1));// true
In these particular cases we could use string methods startsWith/endsWith instead. Regular expressions should be used for more complex tests.
Both anchors together ^...$ are often used to test whether or not a string fully matches the pattern. For instance, to check if the user input is in the right format.
Let’s check whether or not a string is a time in 12:34 format. That is: two digits, then a colon, and then another two digits.
Here the match for \d\d:\d\d must start exactly after the beginning of the text ^, and the end $ must immediately follow.
The whole string must be exactly in this format. If there’s any deviation or an extra character, the result is false.
Anchors behave differently if flag m is present. We’ll see that in the next article.
Anchors have “zero width”
Anchors ^ and $ are tests. They have zero width.
In other words, they do not match a character, but rather force the regexp engine to check the condition (text start/end).
Keep learning JavaScript
Use this lesson as part of a complete JavaScript tutorial path. The topic connects with nearby lessons in the same chapter and supports practical web development skills. See the Learn Regular expressions in JavaScript topic hub for the full lesson cluster.
JavaScript is the programming language of the web, used for interactive pages, browser APIs, servers, tools, and full-stack applications.
Quick questions
What does this JavaScript lesson cover?
This lesson covers Anchors: string start ^ and end $ as part of the Regular expressions chapter in the Additional articles section of the Learn JavaScript Online course.
Who should study Anchors: string start ^ and end $?
Study Anchors: string start ^ and end $ if you want a structured JavaScript tutorial that connects this topic with surrounding lessons, examples, and browser-focused practice.
How does Anchors: string start ^ and end $ fit into learning JavaScript?
Anchors: string start ^ and end $ fits into the course sequence at lesson 7.4, helping you move from JavaScript fundamentals toward practical web development skills.