5. Start and End
Join the Discussion
It is now time to move on and start looking at the characters that have special meanings in regular expressions. We will begin by looking at how we can define a regular expression that is required to match the start or end of a text string rather than just matching any corresponding text. There are three special characters that we are going to look at that have a special meaning when used in a regular expression that will allow us to include the start or end of the string in the match field. These three characters are ^, $, and \.
The ^ character when included in a regular expression matches to the start of the text string.
var re = /^a/i;
This regular expression will only match a string of text if that text starts with an 'a' or 'A' (since we have told it to ignore case).
The $ character when included in a regular expression matches to the end of the text string.
var re = /b$/i;
This regular expression will only match a string of text if that text ends with a 'b' or 'B'. We can of course use both together to specify what the entire string must match.
var re = /^A to Z$/;
This regular expression will only match a text string that consists entirely of the text 'A to Z' with that exact capitalization.
You are probably wondering at this point what the \ character does since I included it in the above list of special characters. You may also be wondering how you can set up a regular expression where you want it to match with ^ or $ characters in the text. Well the answer to both of these questions is the same. The \ character in a regular expression will escape the special meaning of any character that has a special meaning in a regular expression allowing you to reference that character without its special meaning (it is also used in conjunction with characters that don't have a special meaning in order to give them one but we'll get to that later).
var re = /\$100$/;
In this regular expression the first $ is escaped by the \ and therefore represents an actual $ in the text that we want to match while the second $ is not escaped and refers to the end of the text string. The regular expression will therefore match a text string that ends with '$100'.