Regular Expressions: Boundaries
Welcome to the Boundaries lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
Often, we want to match text at the beginning and end of strings. We'll use boundaries for that. The first is
^, which means beginning of string.>
/^cat/.test('cat');Result:
true
>
/^cat/.test('cats are cute');Result:
true
>
/^cat/.test('I like cats');Result:
false
>
/^cat/.test('cats like dogs');Result:
true
>
/^cat/.test('dogs like cats');Result:
false
The second boundary is
$, which means end of string.>
/cat$/.test('a dog');Result:
false
>
/cat$/.test('a cat');Result:
true
>
/cat$/.test('cats');Result:
false
Usually, we want to match an entire string. Most regexes should include these boundaries,
^and$.>
/^a$/.test('a');Result:
true
>
/^a$/.test('the letter a');Result:
false
>
/^a$/.test('a cat');Result:
false
To match only the empty string, we can smash the
^and$together.>
/^$/.test('a');Result:
false
>
/^$/.test(' ');Result:
false
>
/^$/.test('');Result:
true
If we use the wrong boundaries, there's no error. The regex always returns
false.>
/$cat^/.test('cat');Result:
false
If we use boundaries in the wrong place, the regex will always return
false.>
/cat$s/.test('cats');Result:
false
>
/cat^s/.test('cat');Result:
false
One final note about the
^and$boundaries. Above, we said that they match the beginning and end of strings. In most cases, that's true, but only because most regex engines default to "single-line mode": a regex only considers the first line in the string.Regex engines also have "multi-line mode", where a single regex can match any part of a multi-line string. In that mode,
^means "beginning of line" and$means "end of line." They can match characters that are at the beginning or end of a line, even if those characters aren't at the beginning or end of the entire string.Multi-line regexes are their own topic, so we won't cover them in detail here. But in practice, you may see
^referred to as both "beginning of line" and "beginning of string", and likewise for$.