AI Workshop: learn to build apps with AI →
Regular Expressions: Anchoring

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


/hey/

matches hey wherever it appears in the string.

If you want to match strings that start with hey, use the ^ operator:

/^hey/.test('hey')     //✅
/^hey/.test('bla hey') //❌

If you want to match strings that end with hey, use the $ operator:

/hey$/.test('hey')     //✅
/hey$/.test('bla hey') //✅
/hey$/.test('hey you') //❌

Combine those, and match strings that exactly match hey, and just that string:

/^hey$/.test('hey') //✅

To match a string that starts with a substring and ends with another, you can use .*, which matches any character repeated zero or more times:

/^hey.*joe$/.test('hey joe')             //✅
/^hey.*joe$/.test('heyjoe')              //✅
/^hey.*joe$/.test('hey how are you joe') //✅
/^hey.*joe$/.test('hey joe!')            //❌

Lessons in this unit:

0: Introduction
1: Introduction
2: ▶︎ Anchoring
3: Match Items in Ranges
4: Matching a Range Item Multiple Times
5: Negating a Pattern
6: Meta Characters
7: Regular Expressions Choices
8: Quantifiers
9: Optional Items
10: Groups
11: Capturing Groups
12: Using match and exec Without Groups
13: Noncapturing Groups
14: Flags
15: Inspecting a Regex
16: Escaping
17: String Boundaries
18: Replacing
19: Greediness
20: Lookaheads
21: Lookbehinds
22: Unicode
23: Unicode Property Escapes
24: Examples