Skip to main content

Anchors in JavaScript Regular Expressions (Live Playground)

Anchors in JavaScript regular expressions allow you to match specific positions in a string, such as the start or end of a line. In this tutorial, we'll explore different types of anchors and how to use them.

Start of Line Anchor

The caret symbol ^ is used as the start of the line anchor. It matches the position at the beginning of the input string:

const startOfString = /^Hello/; // matches 'Hello' only at the beginning of the string
Live Playground, Try it Yourself

End of Line Anchor

The dollar symbol $ is used as the end of the line anchor. It matches the position at the end of the input string:

const endOfString = /world$/; // matches 'world' only at the end of the string
Live Playground, Try it Yourself

Combining Start and End Anchors

You can combine both start and end anchors to match an entire string:

const exactMatch = /^Hello, world!$/; // matches only the exact string 'Hello, world!'
Live Playground, Try it Yourself

Word Boundary Anchor

The word boundary anchor \b matches the position between a word character (letters, digits, or underscores) and a non-word character. It can be used to find whole words:

const wholeWord = /\bClient\b/; // matches 'Client' as a whole word, not as part of another word
Live Playground, Try it Yourself

Multiline Mode

By default, the start and end anchors ^ and $ match the beginning and end of the entire input string. In multiline mode, they match the start and end of each line within the string. To enable multiline mode, add the m flag:

const multilinePattern = /^First line|^Second line/m; // matches either 'First line' or 'Second line' at the start of a line
Live Playground, Try it Yourself

Conclusion

Anchors are an essential tool in JavaScript regular expressions for matching specific positions in a string. We discussed the start of line anchor ^, end of line anchor $, and word boundary anchor \b. We also covered how to enable multiline mode using the m flag. Understanding how to use anchors effectively will help you create more precise and powerful regular expressions.