Beginning and end

Frequently, we may wish to ensure that a pattern matches at the beginning of a string or perhaps at the end of a string. The caret character, when used as the first character of the RegEx, anchors the match at the beginning of the string such that /^test/ matches only if the test substring appears at the beginning of the string being matched. Similarly, the dollar sign ($) signifies that the pattern must appear at the end of the string: /test$/.

Using both ^ and $ indicates that the specified pattern must encompass the entire candidate string: /^test$/.

Get Mastering JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.